From c63fa018f5618951ab3bcd7c2aec923d7575ad3d Mon Sep 17 00:00:00 2001 From: ToSa27 Date: Sat, 23 Aug 2014 23:59:49 +0200 Subject: [PATCH 001/137] Improved documentation and minor fixes removed examples compiled with outdated MySensors protocol and instead included documentation how to add self-compiled sketches --- Bootloader/Readme.md | 1 + NodeJsController/BlinkGreen.hex | 71 - NodeJsController/BlinkRed.hex | 71 - .../DallasTemperatureSensor.cpp.hex | 1222 ----------------- .../DallasTemperatureSensor.ino | 69 - NodeJsController/NodeJsController.js | 4 +- NodeJsController/{Readme.html => Readme.md} | 19 +- 7 files changed, 12 insertions(+), 1445 deletions(-) create mode 100644 Bootloader/Readme.md delete mode 100644 NodeJsController/BlinkGreen.hex delete mode 100644 NodeJsController/BlinkRed.hex delete mode 100644 NodeJsController/DallasTemperatureSensor.cpp.hex delete mode 100644 NodeJsController/DallasTemperatureSensor/DallasTemperatureSensor.ino rename NodeJsController/{Readme.html => Readme.md} (91%) diff --git a/Bootloader/Readme.md b/Bootloader/Readme.md new file mode 100644 index 0000000..810b16a --- /dev/null +++ b/Bootloader/Readme.md @@ -0,0 +1 @@ +See NodeJsController/Readme.md for usage instructions... \ No newline at end of file diff --git a/NodeJsController/BlinkGreen.hex b/NodeJsController/BlinkGreen.hex deleted file mode 100644 index 00c3de6..0000000 --- a/NodeJsController/BlinkGreen.hex +++ /dev/null @@ -1,71 +0,0 @@ -:100000000C9461000C947E000C947E000C947E0095 -:100010000C947E000C947E000C947E000C947E0068 -:100020000C947E000C947E000C947E000C947E0058 -:100030000C947E000C947E000C947E000C947E0048 -:100040000C949A000C947E000C947E000C947E001C -:100050000C947E000C947E000C947E000C947E0028 -:100060000C947E000C947E00000000002400270009 -:100070002A0000000000250028002B0000000000DE -:1000800023002600290004040404040404040202DA -:100090000202020203030303030301020408102007 -:1000A0004080010204081020010204081020000012 -:1000B0000007000201000003040600000000000029 -:1000C000000011241FBECFEFD8E0DEBFCDBF11E08E -:1000D000A0E0B1E0E4E5F4E002C005900D92A030AC -:1000E000B107D9F711E0A0E0B1E001C01D92A9303D -:1000F000B107E1F70E9418020C9428020C9400004A -:1001000087E061E00E94C4016AEF70E080E090E067 -:100110000E941D0187E060E00E94C4016AEF70E068 -:1001200080E090E00E941D01089587E061E00E9458 -:10013000850108951F920F920FB60F9211242F93ED -:100140003F938F939F93AF93BF93809104019091BE -:100150000501A0910601B0910701309108010196B7 -:10016000A11DB11D232F2D5F2D3720F02D57019696 -:10017000A11DB11D209308018093040190930501F6 -:10018000A0930601B09307018091000190910101B5 -:10019000A0910201B09103010196A11DB11D8093B0 -:1001A000000190930101A0930201B0930301BF915C -:1001B000AF919F918F913F912F910F900FBE0F9014 -:1001C0001F901895789484B5826084BD84B5816051 -:1001D00084BD85B5826085BD85B5816085BDEEE64F -:1001E000F0E0808181608083E1E8F0E0108280812E -:1001F00082608083808181608083E0E8F0E080819C -:1002000081608083E1EBF0E0808184608083E0EBBB -:10021000F0E0808181608083EAE7F0E080818460A3 -:1002200080838081826080838081816080838081FF -:10023000806880831092C1000895EF92FF920F931F -:100240001F93CF93DF937B018C013FB7F89480918C -:10025000000190910101A0910201B091030126B526 -:10026000A89B05C02F3F19F00196A11DB11D3FBFEE -:10027000BA2FA92F982F8827820F911DA11DB11D7C -:1002800052E0880F991FAA1FBB1F5A95D1F7EC01A6 -:1002900030C00E9427023FB7F894809100019091EE -:1002A0000101A0910201B091030126B5A89B05C0F0 -:1002B0002F3F19F00196A11DB11D3FBFBA2FA92FE5 -:1002C000982F8827820F911DA11DB11D32E0880F44 -:1002D000991FAA1FBB1F3A95D1F78C1B9D0B885EF7 -:1002E0009340B8F20894E108F10801091109C851D6 -:1002F000DC4FE114F1040105110559F6DF91CF91AE -:100300001F910F91FF90EF900895CF93DF93482FA7 -:1003100050E0CA0186569F4FFC0134914A575F4F07 -:10032000FA018491882369F190E0880F991FFC01FC -:10033000E859FF4FA591B491FC01EE58FF4FC591CC -:10034000D491662351F42FB7F8948C91932F909504 -:1003500089238C93888189230BC0623061F42FB785 -:10036000F8948C91932F909589238C938881832B7B -:1003700088832FBF06C09FB7F8948C91832B8C93F2 -:100380009FBFDF91CF910895482F50E0CA01825559 -:100390009F4FFC012491CA0186569F4FFC01949106 -:1003A0004A575F4FFA013491332309F440C02223A6 -:1003B00051F1233071F0243028F42130A1F02230A3 -:1003C00011F514C02630B1F02730C1F02430D9F433 -:1003D00004C0809180008F7703C0809180008F7D62 -:1003E0008093800010C084B58F7702C084B58F7D64 -:1003F00084BD09C08091B0008F7703C08091B000A8 -:100400008F7D8093B000E32FF0E0EE0FFF1FEE58DA -:10041000FF4FA591B4912FB7F894662321F48C91E6 -:100420009095892302C08C91892B8C932FBF0895BE -:10043000CF93DF930E94E2000E949500C0E0D0E0DD -:100440000E9480002097E1F30E940000F9CF0895F8 -:04045000F894FFCF4E -:00000001FF diff --git a/NodeJsController/BlinkRed.hex b/NodeJsController/BlinkRed.hex deleted file mode 100644 index 3f2c259..0000000 --- a/NodeJsController/BlinkRed.hex +++ /dev/null @@ -1,71 +0,0 @@ -:100000000C9461000C947E000C947E000C947E0095 -:100010000C947E000C947E000C947E000C947E0068 -:100020000C947E000C947E000C947E000C947E0058 -:100030000C947E000C947E000C947E000C947E0048 -:100040000C949A000C947E000C947E000C947E001C -:100050000C947E000C947E000C947E000C947E0028 -:100060000C947E000C947E00000000002400270009 -:100070002A0000000000250028002B0000000000DE -:1000800023002600290004040404040404040202DA -:100090000202020203030303030301020408102007 -:1000A0004080010204081020010204081020000012 -:1000B0000007000201000003040600000000000029 -:1000C000000011241FBECFEFD8E0DEBFCDBF11E08E -:1000D000A0E0B1E0E4E5F4E002C005900D92A030AC -:1000E000B107D9F711E0A0E0B1E001C01D92A9303D -:1000F000B107E1F70E9418020C9428020C9400004A -:1001000086E061E00E94C4016AEF70E080E090E068 -:100110000E941D0186E060E00E94C4016AEF70E069 -:1001200080E090E00E941D01089586E061E00E9459 -:10013000850108951F920F920FB60F9211242F93ED -:100140003F938F939F93AF93BF93809104019091BE -:100150000501A0910601B0910701309108010196B7 -:10016000A11DB11D232F2D5F2D3720F02D57019696 -:10017000A11DB11D209308018093040190930501F6 -:10018000A0930601B09307018091000190910101B5 -:10019000A0910201B09103010196A11DB11D8093B0 -:1001A000000190930101A0930201B0930301BF915C -:1001B000AF919F918F913F912F910F900FBE0F9014 -:1001C0001F901895789484B5826084BD84B5816051 -:1001D00084BD85B5826085BD85B5816085BDEEE64F -:1001E000F0E0808181608083E1E8F0E0108280812E -:1001F00082608083808181608083E0E8F0E080819C -:1002000081608083E1EBF0E0808184608083E0EBBB -:10021000F0E0808181608083EAE7F0E080818460A3 -:1002200080838081826080838081816080838081FF -:10023000806880831092C1000895EF92FF920F931F -:100240001F93CF93DF937B018C013FB7F89480918C -:10025000000190910101A0910201B091030126B526 -:10026000A89B05C02F3F19F00196A11DB11D3FBFEE -:10027000BA2FA92F982F8827820F911DA11DB11D7C -:1002800052E0880F991FAA1FBB1F5A95D1F7EC01A6 -:1002900030C00E9427023FB7F894809100019091EE -:1002A0000101A0910201B091030126B5A89B05C0F0 -:1002B0002F3F19F00196A11DB11D3FBFBA2FA92FE5 -:1002C000982F8827820F911DA11DB11D32E0880F44 -:1002D000991FAA1FBB1F3A95D1F78C1B9D0B885EF7 -:1002E0009340B8F20894E108F10801091109C851D6 -:1002F000DC4FE114F1040105110559F6DF91CF91AE -:100300001F910F91FF90EF900895CF93DF93482FA7 -:1003100050E0CA0186569F4FFC0134914A575F4F07 -:10032000FA018491882369F190E0880F991FFC01FC -:10033000E859FF4FA591B491FC01EE58FF4FC591CC -:10034000D491662351F42FB7F8948C91932F909504 -:1003500089238C93888189230BC0623061F42FB785 -:10036000F8948C91932F909589238C938881832B7B -:1003700088832FBF06C09FB7F8948C91832B8C93F2 -:100380009FBFDF91CF910895482F50E0CA01825559 -:100390009F4FFC012491CA0186569F4FFC01949106 -:1003A0004A575F4FFA013491332309F440C02223A6 -:1003B00051F1233071F0243028F42130A1F02230A3 -:1003C00011F514C02630B1F02730C1F02430D9F433 -:1003D00004C0809180008F7703C0809180008F7D62 -:1003E0008093800010C084B58F7702C084B58F7D64 -:1003F00084BD09C08091B0008F7703C08091B000A8 -:100400008F7D8093B000E32FF0E0EE0FFF1FEE58DA -:10041000FF4FA591B4912FB7F894662321F48C91E6 -:100420009095892302C08C91892B8C932FBF0895BE -:10043000CF93DF930E94E2000E949500C0E0D0E0DD -:100440000E9480002097E1F30E940000F9CF0895F8 -:04045000F894FFCF4E -:00000001FF diff --git a/NodeJsController/DallasTemperatureSensor.cpp.hex b/NodeJsController/DallasTemperatureSensor.cpp.hex deleted file mode 100644 index a714a35..0000000 --- a/NodeJsController/DallasTemperatureSensor.cpp.hex +++ /dev/null @@ -1,1222 +0,0 @@ -:100000000C94AE020C94311F0C945E1F0C94D6021B -:100010000C94D6020C94D6020C9455140C94D6026F -:100020000C94D6020C94D6020C94D6020C94D602F0 -:100030000C94D6020C94D6020C94D6020C94D602E0 -:100040000C948B1F0C94D6020C9461220C94E42225 -:100050000C94D6020C94D6020C94D6020C94D602C0 -:100060000C94D6020C94D602303B303B25643B25E1 -:10007000643B0072643D636C6561720A0069643DB3 -:1000800025640A0066756C6C0A006E6577207061E5 -:1000900072656E743D25642C20643D25640A0076EB -:1000A000657273696F6E206D69736D61746368004A -:1000B000726561643A2025642D25642D25642073C2 -:1000C0003D25642C633D25642C743D25642C70749F -:1000D0003D25642C6C3D25643A25730A0073656EDA -:1000E000643A2025642D25642D25642D2564207314 -:1000F0003D25642C633D25642C743D25642C70746F -:100100003D25642C6C3D25642C73743D25733A2584 -:10011000730A00726571206E6F64652069640A005D -:10012000636865636B2077697265730A00257320C5 -:10013000737461727465642C2069642025640A00FC -:100140000001020304050A0B0C0D0E0F111213140B -:100150001516A702AD02B302BB02C402CE02D7023B -:10016000DE02E602ED02F402FC02504120506F77FD -:10017000657209203D2025530D0A00435243204C4F -:10018000656E67746809203D2025530D0A004D6F88 -:1001900064656C0909203D2025530D0A00446174F3 -:1001A00061205261746509203D2025530D0A0044E9 -:1001B000594E50442F4645415455524500434F4EE9 -:1001C0004649470052465F53455455500052465FDA -:1001D000434800454E5F52584144445200454E5FEB -:1001E00041410052585F50575F50302D36005458EF -:1001F0005F414444520052585F414444525F503280 -:100200002D350052585F414444525F50302D31002B -:100210000D0A00253032780020307800255309255A -:1002200063203D000D0A002030782530327800250B -:1002300053092563203D004F4253455256455F54B4 -:10024000583D253032783A20504F4C535F434E543E -:100250003D2578204152435F434E543D25780D0A99 -:10026000005354415455530909203D20307825301E -:1002700032782052585F44523D25782054585F44CC -:10028000533D2578204D41585F52543D25782052EA -:10029000585F505F4E4F3D25782054585F46554C6F -:1002A0004C3D25780D0A00314D42505300324D42ED -:1002B0005053003235304B425053006E5246323468 -:1002C0004C3031006E524632344C30312B00446990 -:1002D0007361626C65640038206269747300313642 -:1002E00020626974730050415F4D494E0050415F78 -:1002F0004C4F570050415F484947480050415F4DBF -:10030000415800005EBCE2613FDD83C29C7E20A3B9 -:10031000FD1F419DC3217FFCA2401E5F01E3BD3E46 -:100320006082DC237D9FC1421CFEA0E1BF5D038093 -:10033000DE3C62BEE0025CDF81633D7C22C09E1D2C -:1003400043A1FF4618FAA427799BC584DA3866E5ED -:10035000BB5907DB856739BAE406581947A5FB780E -:1003600026C49A653BD987045AB8E6A7F91B45C647 -:10037000987A24F8A6441A99C7257B3A6486D85BF4 -:1003800005E7B98CD2306EEDB3510F4E10F2AC2FA1 -:100390007193CD114FADF3702ECC92D38D6F31B2DE -:1003A000EC0E50AFF1134DCE90722C6D33D18F0CFB -:1003B00052B0EE326C8ED0530DEFB1F0AE4C1291C4 -:1003C000CF2D73CA947628ABF517490856B4EA695D -:1003D00037D58B5709EBB536688AD495CB2977F496 -:1003E000AA4816E9B7550B88D6346A2B7597C94ABF -:1003F00014F6A8742AC896154BA9F7B6E80A54D77C -:10040000896B3500000000240027002A000000004E -:1004100000250028002B00000000002300260029F2 -:10042000000404040404040404020202020202039D -:1004300003030303030102040810204080010204A7 -:10044000081020010204081020000000070002012B -:100450000000030406000000000000000000407AD5 -:1004600010F35A00A0724E18090010A5D4E800003D -:10047000E87648170000E40B54020000CA9A3B00DB -:100480000000E1F505000080969800000040420F52 -:10049000000000A08601000000102700000000E816 -:1004A00003000000006400000000000A00000000DB -:1004B000000100000000002C76D888DC674F08237C -:1004C000DFC1DFAE59E1B1B796E5E3E453C63AE6E2 -:1004D00051997696E8E6C28426EB898C9B62ED40C2 -:1004E0007C6FFCEFBC9C9F40F2BAA56FA5F4900511 -:1004F0005A2AF75C936B6CF9676DC11BFCE0E40D45 -:1005000047FEF520E6B500D0ED902E030094357738 -:10051000050080841E080000204E0A000000C80C60 -:10052000333333330F986E12831141EF8D211489C9 -:100530003BE65516CFFEE6DB18D1844B381BF77C23 -:100540001D901DA4BBE424203284725E228100C968 -:10055000F124ECA1E53D27003F09972211241FBE9D -:10056000CFEFD8E0DEBFCDBF11E0A0E0B1E0E4EE18 -:10057000FBE402C005900D92A036B107D9F713E055 -:10058000A0E6B1E001C01D92A930B107E1F715E086 -:10059000CCE5D5E004C02297FE010E94A125C83514 -:1005A000D107C9F70E940A230C94F0250C9400008F -:1005B000EF92FF920F931F93F22FF02E47FD02C090 -:1005C000E4E001C0E4E1242F332727FD309537FF15 -:1005D00003C0309521953F4F4F2D512F0F2FEE2EF9 -:1005E0000E9455068F2D912F1F910F91FF90EF9034 -:1005F0000895FC0188279927E89421912032E9F396 -:10060000293010F02E30C8F32B3241F02D3239F45E -:10061000689404C00E94DA03820F911D2191205337 -:100620002A30C0F31EF4909581959F4F08951F9333 -:10063000FC0199278827BC01E89411911032E9F355 -:10064000193010F01E30C8F31B3251F01D3249F43E -:10065000689406C00E94C503610F711D811D911D24 -:10066000119110531A30B0F33EF490958095709527 -:1006700061957F4F8F4F9F4F1F910895FB01DC01C4 -:1006800001900D920020E1F70895FB01DC0141503B -:10069000504048F001900D920020C9F701C01D9212 -:1006A00041505040E0F70895A0E0B0E0EAE5F3E003 -:1006B0000C94C3257C01EB018A01690109C0CE01BC -:1006C0002196F6010995F70181937F0101501040B1 -:1006D00001151105A1F7CDB7DEB7E8E00C94DF25D1 -:1006E000FB019F01E8944230C4F04532B4F44A3033 -:1006F00029F497FB1EF4909581959F4F642F7727DF -:100700000E94A525805D8A330CF0895D8193CB0121 -:100710000097A1F716F45DE251931082C9010C9481 -:10072000A508FA01CF93FF93EF93223044F12532CD -:1007300034F5C22FE894CA3049F497FB3EF4909503 -:100740008095709561957F4F8F4F9F4F2C2F33274A -:1007500044275527FF93EF930E947D25EF91FF914A -:10076000605D6A330CF0695D6193B901CA01605044 -:1007700070408040904051F716F4CDE2C193108252 -:100780008F919F91CF910C94A508592F482F372F07 -:10079000262F660F771F881F991F660F771F881FE8 -:1007A000991F620F731F841F951F660F771F881F85 -:1007B000991F08957AE0979F902D879F802D910D26 -:1007C00011240895FA01CF93FF93EF932230CCF0D8 -:1007D0002532BCF4C22F2C2F332744275527FF93F3 -:1007E000EF930E947D25EF91FF91605D6A330CF0DD -:1007F000695D6193B901CA016050704080409040CA -:1008000051F710828F919F91CF910C94A508FB0115 -:100810009F01423074F0453264F4642F77270E94C0 -:10082000A525805D8A330CF0895D8193CB0100970B -:10083000A1F71082C9010C94A508AEE0B0E0E3E294 -:10084000F4E00C94C7250D891E898F89988D97FF38 -:1008500002C080E090E801979E838D831A8309830C -:100860008EE08C839E01255E3F4FCE010196698DFF -:100870007A8DA9010E9478044D815E8157FD0AC0DE -:100880002F813885421753070CF49A01020F131F6A -:10089000F80110822E96E4E00C94E325AEE0B0E07F -:1008A000E4E5F4E00C94C7258C0177FF02C060E01A -:1008B00070E8615070407E836D831A8309838EE0F7 -:1008C0008C83CE010196BA01A9010E9478042D8182 -:1008D0003E8137FD09C0EF81F8852E173F070CF4E4 -:1008E000F901E00FF11F10822E96E4E00C94E3254D -:1008F000ABE0B0E0EEE7F4E00C94B9253C012B014D -:100900005A01FC0117821682838181FD03C06FEFBB -:100910007FEFC6C19AE0892E1E010894211C311C6C -:10092000F3012381F20123FD859123FF81912F01A2 -:10093000882309F4B2C1853239F423FD859123FF60 -:1009400081912F01853229F490E0B3010E94B5080E -:10095000E7CF982FFF24EE249924FFE1FF15D0F074 -:100960009B3269F09C3228F4903259F0933291F422 -:100970000EC09D3249F0903369F441E024C052E04A -:10098000F52A84E0F82A28C098E0F92A25C0E0E199 -:10099000FE2A22C0F7FC29C0892F80538A3070F4C8 -:1009A000F6FE05C0989C902C1124980E15C0E89C6A -:1009B000E02C1124E80EF0E2FF2A0EC09E3229F44A -:1009C000F6FC6BC140E4F42A07C09C3619F450E8E9 -:1009D000F52A02C0983649F4F20123FD959123FFD0 -:1009E00091912F01992309F0B8CF892F8554833035 -:1009F00018F08052833038F444E050E0A40EB51E65 -:100A00005FE359830FC0933631F0933779F0933514 -:100A100009F056C020C0F5018081898342E050E092 -:100A2000A40EB51E610101E010E012C0F501C08006 -:100A3000D180F6FC03C06FEF7FEF02C0692D70E03C -:100A400042E050E0A40EB51EC6010E949A088C0137 -:100A50005FE7F52214C0F501C080D180F6FC03C029 -:100A60006FEF7FEF02C0692D70E042E050E0A40E0E -:100A7000B51EC6010E948F088C0150E8F52AF3FECE -:100A800007C01AC080E290E0B3010E94B508EA9462 -:100A90008E2D90E008171907A8F30EC0F601F7FC99 -:100AA0008591F7FE81916F0190E0B3010E94B50836 -:100AB000E110EA94015010400115110579F7EAC0E0 -:100AC000943611F0993669F5F7FE08C0F5012081DA -:100AD00031814281538184E090E00AC0F501808138 -:100AE00091819C01442737FD4095542F82E090E08E -:100AF000A80EB91E9FE6F92257FF09C050954095F0 -:100B0000309521953F4F4F4F5F4FE0E8FE2ACA01D5 -:100B1000B901A1012AE030E00E94E108D82ED218E4 -:100B200040C0953729F41F2D1F7E2AE030E01DC0FC -:100B30001F2D197F9F3661F0903720F4983509F00A -:100B4000ACC00FC0903739F0983709F0A6C004C088 -:100B500028E030E00AC0106114FD146020E130E0AC -:100B600004C014FD166020E132E017FF08C0F50153 -:100B7000608171818281938144E050E008C0F50179 -:100B800080819181BC0180E090E042E050E0A40EC1 -:100B9000B51EA1010E94E108D82ED2188FE7F82EC9 -:100BA000F122F6FE0BC05EEFF522D91438F4F4FE04 -:100BB00007C0F2FC05C08FEEF82202C01D2D01C057 -:100BC000192DF4FE0DC0FE01ED0DF11D8081803365 -:100BD00019F499EEF92208C01F5FF2FE05C003C0A8 -:100BE0008F2D867809F01F5F0F2DF3FC14C0F0FEE7 -:100BF0000FC01E1510F09D2C0BC09D2C9E0C911A41 -:100C00001E2D06C080E290E0B3010E94B5081F5F70 -:100C10001E15C0F304C01E1510F4E11A01C0EE2425 -:100C200004FF0FC080E390E0B3010E94B50802FF0B -:100C30001DC001FD03C088E790E00EC088E590E08C -:100C40000BC0802F867891F001FF02C08BE201C0BB -:100C500080E2F7FC8DE290E0B3010E94B50806C087 -:100C600080E390E0B3010E94B5089A94D914C0F3D0 -:100C7000DA94F101ED0DF11D808190E0B3010E9445 -:100C8000B508DD20A9F706C080E290E0B3010E941C -:100C9000B508EA94EE20C1F743CEF301668177816F -:100CA000CB012B96E2E10C94D525A9E0B0E0EBE571 -:100CB000F6E00C94BD256A01122FA02EBE2C2BE36A -:100CC000201718F42CE3922E02C0902E9394AE01BC -:100CD0004F5F5F4F27E0092D0E94B707BC01898154 -:100CE000E82EFF24C70189709070019711F4ADE2DE -:100CF00009C0B1FE02C0ABE205C0B0FC02C0A0E07A -:100D000001C0A0E2E3FE3BC0AA2311F423E001C02E -:100D100024E0211710F020E002C0121B212FEB2C41 -:100D2000B4FE02C0322F0AC0F601322F80E202C0A8 -:100D3000819331503323E1F7C20ED11CAA2319F05D -:100D4000F601A1936F01F6013196E2FE05C09EE423 -:100D5000D6019C9381E404C09EE6D6019C9381E673 -:100D600011968C9391833296DF01832F90E202C01B -:100D70009D9381508823E1F7E30FF11D40C0E2FE0F -:100D800042C0AA2311F423E001C024E0211710F08F -:100D900020E002C0121B212FEB2CB4FE02C0922FC8 -:100DA0000AC0F601922F80E202C0819391509923EC -:100DB000E1F7C20ED11CAA2319F0F601A1936F012D -:100DC000F6013196E2FE08C089E4D6018C938EE4E8 -:100DD00011968C9386E407C089E6D6018C938EE643 -:100DE00011968C9386E681833296DF01892F20E26B -:100DF00002C02D9381508823E1F7E90FF11D108285 -:100E00002EEF3FEFAFC0161617061CF041E050E082 -:100E100003C0AB014F5F5F4FAA2019F480E090E060 -:100E200003C08A2D90E0019620E030E0AA2311F063 -:100E300021E030E0240F351F280F391F812F90E06B -:100E40002817390714F020E002C0121B212F4B2D68 -:100E500050E0CA0180719070B4FC0DC0B3FC0BC0AF -:100E6000F601322F40E202C0419331503323E1F7C3 -:100E7000C20ED11C01C0322FAA2319F0F601A19392 -:100E80006F01892B11F0132F0AC0F601132F80E395 -:100E900002C0819311501123E1F7C30ED11C092D1B -:100EA000060FBA8090E1892E912C8E209F20E4FEBF -:100EB00004C0F1E3BF1609F40150101614F001E06C -:100EC00003C0093008F008E09B0177FF02C020E072 -:100ED00030E0CB010196821B930BFE013196E80FA7 -:100EE000F91F8EE2F82E3B01601A71088A2D90E0FE -:100EF00044275527481B590B8FEF2F3F380719F40C -:100F0000D601FD926D01621773072CF0621673060D -:100F100014F4808101C080E32150304031962417C1 -:100F2000350724F0D6018D936D01E6CF26173707DC -:100F300049F4B5E3BB1528F0BB1621F481149104E4 -:100F400009F481E3F6018193D601812F90E202C07A -:100F50009C93815011968823D9F7E10FF11D1082DF -:100F600020E030E0C9012996EEE00C94D925283024 -:100F700008F027E03327DA01990F311D87FD9160D2 -:100F800000966105710539F432602E5F3D9330E3C0 -:100F90002A95E1F708959F3F30F08038710561058B -:100FA00009F03C5F3C5F3D93913008F08068911DF3 -:100FB000DF93CF931F930F93FF92EF92192F987F98 -:100FC0009695E92F96959695E90FFF27E954FB4FE3 -:100FD00099273327EE24FF24A701E7010590089401 -:100FE000079428F4360FE71EF81E491F511D660F9F -:100FF000771F881F991F0694A1F70590079428F47E -:10100000E70EF81E491F561FC11D770F881F991F35 -:10101000661F0694A1F70590079428F4F80E491F5F -:10102000561FC71FD11D880F991F661F771F069473 -:10103000A1F70590079420F4490F561FC71FD81F2A -:10104000990F661F771F881F0694A9F78491109542 -:10105000177041F0D695C79557954795F794E79443 -:101060001A95C1F7EDE5F4E0689415901591359166 -:101070006591959105907FE27395E118F10A430B14 -:10108000560BC90BD009C0F7E10CF11E431F561FC8 -:10109000C91FD01D7EF4703311F48A95E6CFE89411 -:1010A000015030F0080F0AF40027021708F4202F2F -:1010B0002395022F7A3328F079E37D932A95E9F777 -:1010C00010C07D932A9589F6069497956795379574 -:1010D00017951794E118F10A430B560BC90BD00969 -:1010E00098F023957E9173957A3308F070E37C93A2 -:1010F0002013B8F77E9170617D9330F0839571E392 -:101100007D9370E32A95E1F71124EF90FF900F9102 -:101110001F91CF91DF91992787FD90950895FC014C -:101120000590615070400110D8F7809590958E0F12 -:101130009F1F0895FC016150704001900110D8F785 -:10114000809590958E0F9F1F0895DC01FC01672FFD -:1011500071917723E1F7329704C07C916D9370838E -:101160006291AE17BF07C8F308950F931F93CF93F3 -:10117000DF938C01EB018B8181FF1BC082FF0DC0CF -:101180002E813F818C819D812817390764F4E88185 -:10119000F9810193F983E88306C0E885F985802FFA -:1011A0000995892B31F48E819F8101969F838E83CF -:1011B00002C00FEF1FEFC801DF91CF911F910F9178 -:1011C0000895FA01AA27283051F1203181F1E894DD -:1011D0006F936E7F6E5F7F4F8F4F9F4FAF4FB1E02A -:1011E0003ED0B4E03CD0670F781F891F9A1FA11D25 -:1011F000680F791F8A1F911DA11D6A0F711D811D26 -:10120000911DA11D20D009F468943F912AE0269FEA -:1012100011243019305D3193DEF6CF010895462F49 -:101220004770405D4193B3E00FD0C9F7F6CF462F2A -:101230004F70405D4A3318F0495D31FD4052419393 -:1012400002D0A9F7EACFB4E0A69597958795779550 -:101250006795BA95C9F700976105710508959B01D7 -:10126000AC010A2E06945795479537952795BA9560 -:10127000C9F7620F731F841F951FA01D08950F9358 -:101280001F9300E611E0C80163E00E94C61D8EE6D0 -:1012900091E0B8010E941D1980E891E069E04AE000 -:1012A0000E94F71389E392E060E040E00E94410A67 -:1012B0001F910F910895CF92DF92EF92FF920F93BB -:1012C0001F93CF93DF9380E891E00E94870D8EE615 -:1012D00091E00E94121A87EFC82E81E0D82EC0E05C -:1012E000D0E056C080E891E00E94290B882331F0BD -:1012F0008EE691E06C2F0E94351B05C08EE691E0D2 -:101300006C2F0E945C1B20E030E040E251E40E9420 -:101310001A250E943724882777FD8095982F0E94F0 -:101320006A2420E030E040E251E40E94CF237B01B8 -:101330008C01F6016081718182819381A8019701FE -:101340000E94CB238823F9F0C801B70120E030E0E8 -:101350004EEF52EC0E94CB238823A9F089E392E060 -:101360006C2F0E94460AB801A70121E00E94550A8D -:10137000BC0180E891E040E00E942F12F601E0827B -:10138000F18202831383219684E090E0C80ED91E77 -:101390008091370290913802C817D90724F4C031E0 -:1013A000D10509F09FCF609140017091410180917A -:1013B0004201909143010E94262080E891E00E9422 -:1013C000870D609144017091450180E891E00E9491 -:1013D0008E0CDF91CF911F910F91FF90EF90DF90D6 -:1013E000CF900895AF92BF92CF92EF92FF920F935A -:1013F000CF93DF938EE691E00E946B1B80E891E033 -:1014000060E070E04FEF20E00FEFE3E0EE2EF12C14 -:101410005CE4C52E32E0A32EB12C0E94C11280E8FC -:1014200091E060E071E043E151E020E00E94BF11F3 -:101430008EE691E00E942B198093370210923802B9 -:10144000C0E0D0E008C080E891E06C2F46E020E0EA -:101450000E940D1221968091370290913802C81790 -:10146000D9071CF4C031D10571F7DF91CF910F91ED -:10147000FF90EF90CF90BF90AF900895FC01148241 -:101480000895FC011482668345830895FC016683F8 -:101490000895FC01808187708860808381818F70CE -:1014A000806181836783CF010895CF92DF92EF92AD -:1014B000FF920F931F937C01F7E0CF2ED12CC80E23 -:1014C000D91ECB01BA0142E086010E94D802F60182 -:1014D00001900020E9F73197EC19FD09EE0FEE0FAE -:1014E000EE0FD7018C918770E82BEC9311968C91BD -:1014F00011978F7011968C93C7011F910F91FF90D8 -:10150000EF90DF90CF900895CF93DF93EC01DB0154 -:101510000D900020E9F71197A61B4A2F50E09A0181 -:10152000B3E0220F331FBA95E1F788818770822BD1 -:10153000888389818F708983A93110F049E150E057 -:10154000CE0107960E944503CE01DF91CF91089509 -:10155000FC01818182958F7090E0009731F00197B6 -:1015600011F080E0089587810895CF0107960E94C9 -:10157000F9020895FC01818182958F7090E00097B7 -:1015800061F0059729F020E030E040E050E00EC027 -:10159000278130854185528509C0CF0107960E9479 -:1015A0001703AC01CB01DA019C01AD01B901CA01FD -:1015B0000895CF93DF93FC01EB01818182958F70B9 -:1015C00031F43796CB01BF010E943E0336C061154E -:1015D000710599F18330B9F0843028F4813041F0FD -:1015E000823059F508C08430A9F0853031F51CC02F -:1015F000878190E002C087819085BE014AE050E07B -:101600000E9470031AC0878190854AE050E00E94D2 -:10161000070413C06781708581859285AE012AE039 -:1016200030E00E94910309C06781708581859285B1 -:10163000AE012AE030E00E94E203CE01DF91CF91BB -:1016400008959C01F999FECF32BD21BDF89A80B56D -:101650000895FC0181890895EF92FF920F931F93E3 -:10166000DF93CF93CDB7DEB7CC52D1400FB6F8940D -:10167000DEBF0FBECDBFC95CDE4FE880F980C75327 -:10168000D140CB5CDE4FA881B981C553D14054967F -:101690008C91882389F1EDB7FEB73A970FB6F8948D -:1016A000FEBF0FBEEDBF31968E010F5F1F4FADB76E -:1016B000BEB712961C930E9311978BE291E0938321 -:1016C000828388E690E09583848383E090E097832B -:1016D000868389E090E0918780870E941D04EDB7A2 -:1016E000FEB73A960FB6F894FEBF0FBEEDBF88E680 -:1016F00092E0B8010E946223FE01E75CFE4FCB5CE2 -:10170000DE4FA881B981C553D14054968C919E017A -:101710002F5F3F4F882359F0C9016CE370E0A701A8 -:101720009F010E944E048AE08CAF1DAE07C0C90124 -:101730006BE271E0A7019F010E944E0488E692E0EF -:10174000BE016F5F7F4F0E94622388E692E00E9495 -:10175000EF21C45DDE4F0FB6F894DEBF0FBECDBFE4 -:10176000CF91DF911F910F91FF90EF900895CF934C -:10177000DF93EB010CC08AE592E069E070E040E0A5 -:1017800050E020E030E00E940714C054DF41809117 -:10179000480190914901892B89F08FE1C034D80725 -:1017A00054F7B3C08AE592E068E070E040E050E0B2 -:1017B00020E030E00E940714C05ADF4080914801C9 -:1017C00090914901892B81F087E0C03DD80764F0F2 -:1017D0008AE592E067E070E040E050E020E030E031 -:1017E0000E940714C05DD740809148019091490143 -:1017F000892B81F083E0C83ED80764F08AE592E047 -:1018000066E070E040E050E020E030E00E94071425 -:10181000C85ED3408091480190914901892B81F0A5 -:1018200081E0C43FD80764F08AE592E065E070E0AB -:1018300040E050E020E030E00E940714C45FD14057 -:101840008091480190914901892B79F0CA3FD105D7 -:1018500064F08AE592E064E070E040E050E020E06F -:1018600030E00E940714CA5FD040809148019091F7 -:101870004901892B79F0CD37D10564F08AE592E0F2 -:1018800063E070E040E050E020E030E00E940714A8 -:10189000C857D0408091480190914901892B71F03F -:1018A000C034D1055CF08AE592E062E070E040E08F -:1018B00050E020E030E00E940714EC97809148014E -:1018C00090914901892B71F0C032D1055CF08AE515 -:1018D00092E061E070E040E050E020E030E00E9403 -:1018E00007146E978091480190914901892B99F0D6 -:1018F00060978CF08AE592E060E070E040E050E0B4 -:1019000020E030E00E94071406C08FE0C03AD807FC -:101910000CF454CF47CFDF91CF910895EF92FF920F -:101920000F931F938C017B0188E692E00E94EF21C8 -:10193000C8010E942C1881E090E0909349018093A7 -:101940004801C801B7010E94B70B1F910F91FF908A -:10195000EF9008955F926F927F928F929F92AF92D5 -:10196000BF92CF92DF92EF92FF920F931F93CF938C -:10197000DF937C01562EEA01822E8881982E969460 -:1019800096949694D7011E969C919B83887F826043 -:101990008883DE2CCF2CC7010E941118C7010E943A -:1019A000411830E040E050E060E070E080E090E01E -:1019B000052DF1E03D3F08F4F0E0E1E0423E08F49F -:1019C000E0E031EEA32EAF0EE060F1E0593A08F40A -:1019D000F0E028EAB22EBE0EE1E0B8EABB1608F04D -:1019E000E0E0FE2BA1E0693A08F4A0E0BF2FB85573 -:1019F000E1E0B83A08F0E0E0AE2BF1E0772309F43B -:101A0000F0E0E1E0882309F4E0E08D2D9C2D1CEF4F -:101A100095014B2F5A2F6F2F7E2F0E945216892D22 -:101A200090E04A9714F040E202C0492D495F8D2DA5 -:101A30009C2DBE01282D0E940516682E8D2D9C2DF3 -:101A40000E945C18BA80AB809C808E8019817D805A -:101A50000881662029F497E1C92E91E0D92E04C0AF -:101A60008CE1C82E81E0D82EB701695A7F4FCE0194 -:101A70000E94D90AEDB7FEB77A970FB6F894FEBF69 -:101A80000FBEEDBF3196ADB7BEB71296FC92EE9287 -:101A900011972DED30E033832283B4821582A68224 -:101AA0001782508611869286138684861586212F8A -:101AB00030E02770307037872687708A118A129538 -:101AC0001F70128B138A069506950695048B158A4E -:101AD000D78AC68A918F808F0E942C0BEDB7FEB7F4 -:101AE0007A960FB6F894FEBF0FBEEDBF862DDF913C -:101AF000CF911F910F91FF90EF90DF90CF90BF900B -:101B0000AF909F908F907F906F905F9008954F92CD -:101B10005F926F927F928F929F92AF92BF92CF927D -:101B2000DF92EF92FF920F931F93DF93CF930F9269 -:101B3000CDB7DEB74C01582E492C8E010F5F1F4FD9 -:101B4000B8010E94F217882309F4D5C28981873031 -:101B500008F0D1C2C4010E940215482F65E1662E2B -:101B6000712C680C791CC401B3010E94F815C401E2 -:101B70006981A80121E00E949414D40155960C912A -:101B800006950695069510E0F401E00FF11F148EFE -:101B9000F401E788D08CC18CB38CF688A28CB40198 -:101BA000695A7F4FC3010E94D90A2DB73EB726510B -:101BB00030400FB6F8943EBF0FBE2DBFEDB7FEB755 -:101BC0003196ADB7BEB712969C928E92119720EBCC -:101BD00030E033832283E4821582D6821782C08666 -:101BE0001186B28613862F2D30E02770307035872E -:101BF0002487A6861786F2945FE0F522F08A118A80 -:101C0000138B028B958B848B0E942C0BF40185899E -:101C100087702DB73EB72A5E3F4F0FB6F8943EBF90 -:101C20000FBE2DBF8230B1F000D000D0ADB7BEB72F -:101C300012969C928E9211978FE990E014969C9345 -:101C40008E9313970E942C0B80E00F900F900F90B3 -:101C50000F9052C2F4012689022F0770128DE78877 -:101C6000F08C318D9289992379F1033069F5173021 -:101C700059F50E94D31F7370807090700E942620C7 -:101C8000D4011E968C911E9757968C935797599610 -:101C9000EC9259978FEF5B968C935B9788E05A96FE -:101CA0008C935A9756968C915697807F8360569660 -:101CB0008C935697C30150966C910E94490AAC01CF -:101CC000C4016E2D21E0F5C1F4018685381709F0B5 -:101CD000DBC123FF21C0D401D696759681E2019025 -:101CE0000D928150E1F7D401D7968C91D797877FD9 -:101CF000D7968C93D7971E968C911E97D8968C93D7 -:101D0000D89757968C915797DA968C93B4016A5C62 -:101D10007F4FC4010E945011F4018289882319F178 -:101D20008785F81601F12E2D30E081E790E0880ECE -:101D3000991ED401ED91FC918FE89FEF880E991EBA -:101D4000E20FF31F80818F1571F0F082F999FECFB9 -:101D50001FBA2D5F3F4F32BD21BDF0BC0FB6F894C6 -:101D6000FA9AF99A0FBE033009F081C1183009F0D0 -:101D700053C0D40154968C91882309F04DC0C301FF -:101D80000E94A80A482F282F30E0F401808990E0B3 -:101D90000197281739070CF0AEC14F5F408B278998 -:101DA0002787F999FECF1FBA81E090E092BD81BDEF -:101DB00020BD0FB6F894FA9AF99A0FBED401509646 -:101DC0003C91F999FECF1FBA82E090E092BD81BDAF -:101DD00030BD0FB6F894FA9AF99A0FBEEDB7FEB778 -:101DE00038970FB6F894FEBF0FBEEDBF3196ADB772 -:101DF000BEB712969C928E9211978AE890E09383D8 -:101E0000828324831582368317820E942C0B80E004 -:101E1000EDB7FEB73896A3C0EE2009F028C1163002 -:101E200009F4A3C0173038F4113009F40FC114308D -:101E300009F061C112C01A3009F4B0C01D3009F0B8 -:101E40005AC128E088E190E00FB6F894A8958093F5 -:101E500060000FBE20936000FFCFD4011E968C91CE -:101E60008F3F09F048C1C3010E94A80AF401868788 -:101E70008F3FA9F400D000D0ADB7BEB712969C92A8 -:101E80008E92119784E890E014969C938E9313970A -:101E90000E942C0B0F900F900F900F90FFCF282FC8 -:101EA00030E040E050E060E070E080E090E0E22E62 -:101EB00001E03D3F08F400E011E0423E08F410E08C -:101EC0000F511060E1E0593A08F4E0E01855F1E0F4 -:101ED000183A08F0F0E0EF2BF1E0693A08F4F0E08E -:101EE000BE2FB855E1E0B83A08F0E0E0FE2BA1E0E3 -:101EF000772309F4A0E0E1E0882309F4E0E0852DF0 -:101F0000942D61E04CEFF42E2B2F3F2F4A2F5E2FA4 -:101F10000E947317F4012685F999FECF1FBA12BCEF -:101F200011BC20BD0FB6F894FA9AF99A0FBE00D0F2 -:101F300000D000D0EDB7FEB73196ADB7BEB7129660 -:101F40009C928E9211978DE790E0938382832483F5 -:101F500015820E942C0B80E0EDB7FEB736960FB6C7 -:101F6000F894FEBF0FBEEDBFC7C0C3010E94A80A10 -:101F700020E08D3409F421E0D40151968C915197E1 -:101F8000821709F4B8C051962C93F999FECF1FBA65 -:101F900083E091E092BD81BD20BDA8C0F40182899B -:101FA000882309F4A8C0C3010E94A80A833409F059 -:101FB000A2C000D000D0ADB7BEB712969C928E9250 -:101FC000119783E790E014969C938E9313970E9449 -:101FD0002C0B20E030E00F900F900F900F90D40169 -:101FE000AF58BF4F9FEFED91FC911197E20FF31F98 -:101FF00080818F3F81F09083F999FECF1FBA2D5FCA -:102000003F4F32BD21BD2350304090BD0FB6F894F4 -:10201000FA9AF99A0FBE2F5F3F4F2230310519F718 -:10202000F4018685878B118E8FEF838F8AE0828FF4 -:102030008689807F8360868BC3016FE171E00E9497 -:10204000840ABC01C4010E94501155C023E730E04E -:10205000820E931ED4010D911C910115110509F4F6 -:102060004AC0C3010E94BA0AF801099544C0E5E7D5 -:10207000F0E08E0E9F1ED401ED91FC91309711F08F -:10208000C301099581E038C09923A9F18981813084 -:1020900091F584010F581F4FD801ED91FC91E30F8A -:1020A000F11D6081862F81508E3F30F4C401A30161 -:1020B00020E00E94AA0C1FC0C401F4016785A3019F -:1020C00020E00E94AA0C6E2D70E0D801ED91FC91E9 -:1020D000E60FF71F80818F1571F0F082F999FECF1E -:1020E0001FBA6D5F7F4F72BD61BDF0BC0FB6F89433 -:1020F000FA9AF99A0FBE80E00F90CF91DF911F916D -:102100000F91FF90EF90DF90CF90BF90AF909F9096 -:102110008F907F906F905F904F900895EF92FF9215 -:102120000F931F93CF93DF93EC010E94D31F7B018A -:102130008C0103C0CE010E94870D0E94D31F6E192F -:102140007F09800B910B605D77408040904090F359 -:10215000DF91CF911F910F91FF90EF900895EF9233 -:10216000FF920F931F938C0100591F4FF8011082AB -:10217000005710409FEFF801908B8685878B918FD9 -:10218000938F87E0828F8689807F8360868B75E15D -:10219000E72EF12CE00EF11EC7016FE171E00E9405 -:1021A000840AC8016FEFA70121E00E94AA0CC801B0 -:1021B0000E948E101F910F91FF90EF900895EF9263 -:1021C000FF920F931F93CF93DF93EC0100D000D0C9 -:1021D000EDB7FEB79283818383E191E0948383839B -:1021E0000E942C0B0F900F900F900F908E85282F30 -:1021F00030E040E050E060E070E080E090E0E22E0F -:1022000001E03D3F08F400E011E0423E08F410E038 -:102210000F511060E1E0593A08F4E0E01855F1E0A0 -:10222000183A08F0F0E0EF2BF1E0693A08F4F0E03A -:10223000BE2FB855E1E0B83A08F0E0E0FE2BA1E08F -:10224000772309F4A0E0E1E0882309F4E0E0CE017F -:1022500061E02CEFF22E2B2F3F2F4A2F5E2F0E9492 -:1022600073178E858F8B198E8FEF8B8F83E08A8FFC -:102270008E89807F83608E8BCE0145966FE171E001 -:102280000E94840ABC01CE010E945011CE010E941E -:102290008E10DF91CF911F910F91FF90EF900895D5 -:1022A0001F93CF93DF93EC01DB0120E011968C911B -:1022B00011978770833009F421E08E858F3F59F4A0 -:1022C000222329F015968C911597833021F0CE01A9 -:1022D0000E94DF102CC08A89882331F114969C91CA -:1022E0001497CF58DF4FE881F981C157D040E90FEB -:1022F000F11D6081862F81508E3F30F4992321F0AB -:10230000CE01AD0120E00DC0222371F015968C9115 -:102310001597843049F49F3F39F4CE016FEFAD013A -:1023200021E00E94AA0C27C08C89882311F080E04C -:1023300022C0CE016F85AD0120E00E94AA0C182FAB -:10234000882329F011E0C059DF4F188213C08B8910 -:10235000882351F0C059DF4F8881C057D040863064 -:1023600018F0CE010E94AF10FE01E059FF4F8081AE -:102370008F5F8083812FDF91CF911F910895FF920E -:102380000F931F93CF93DF93EC018A01F22E611517 -:102390007105E1F08E858F8B198E8FEF8B8F8BE01F -:1023A0008A8F30E02170307053E0220F331F5A952E -:1023B000E1F78E89807F8360822B8E8BCE014596DC -:1023C0000E94840ABC01CE010E9450110115110522 -:1023D000F1F08E858F8B198E8FEF8B8F8CE08A8F2B -:1023E0002F2D30E02170307043E0220F331F4A95CB -:1023F000E1F78E89807F8360822B8E8BCE0145969C -:10240000B8010E94840ABC01CE010E945011DF91E4 -:10241000CF911F910F91FF9008950F931F938C01FF -:10242000FC018685878B118E638F428F30E021708F -:10243000307063E0220F331F6A95E1F78689807F51 -:10244000822B868BC801459660E271E00E94840A67 -:10245000BC01C8010E9450111F910F910895DC0129 -:10246000FB011E968C911E97828350E04170507044 -:1024700083E0440F551F8A95E1F78181807F816059 -:10248000842B8183CD010E945011811181E0089538 -:102490000F931F938C0180E091E00E9419230F5845 -:1024A0001F4FF8018083918363E070E040E051E0CA -:1024B00021E23BE00E9454031F910F910895EF9297 -:1024C000FF920F931F93CF93DF93EC01E62EF42E30 -:1024D0008901C059DF4F1882C057D040CE010E94F9 -:1024E0009518CE010E947A14882389F400D000D078 -:1024F000EDB7FEB7D283C18380E291E094838383FA -:102500000E942C0B0F900F900F900F90FFCFCE01D9 -:1025100061E00E94EE15CE0162E040E00E940C17DF -:10252000CE010E943817CE016F2D0E941F16CE01DA -:102530006E2D0E94F316CE01B8010E94C216CE0184 -:1025400065E04FE00E94E415CE0162E070E00E9479 -:10255000A716CE010E945417CE0162E0EE24EA9441 -:102560002CEFF22E01EE18EA28EA30E040E050E0CD -:102570000E947317DF91CF911F910F91FF90EF9001 -:1025800008958F929F92AF92BF92CF92DF92EF9277 -:10259000FF920F931F93CF93DF93EC014B01D42E47 -:1025A000122F88E692E040E052EC61E070E026E015 -:1025B0000E9451211C8A1A8A112311F081E08A8B12 -:1025C000CB58DF4F99828882C557D0408A898823AB -:1025D00019F0CE010E944812CE01B7014C2D950191 -:1025E0000E945F12CE010E9660E070E043E050E082 -:1025F00021E23BE00E945403CE01419663E271E088 -:1026000041E050E021E23BE00E94540389898F3F82 -:1026100011F481E0898B0F3F19F00F871B8A02C0EC -:1026200081E08B8B8FEFD812DE868B89882331F087 -:102630008F858F3F19F4CE010E94AF108E858F3F9A -:1026400019F4CE010E94DF108A89882319F420E34F -:1026500031E002C027E331E0ADB7BEB718970FB63F -:10266000F894BEBF0FBEADBFEDB7FEB73196129660 -:10267000DC93CE9311978DE291E09383828335832F -:1026800024838E85868317820E942C0BDC2ECD2E10 -:102690008DB79EB708960FB6F8949EBF0FBE8DBF3C -:1026A0008E85282F30E040E050E060E070E080E070 -:1026B00090E0E22E01E03D3F08F400E011E0423EF0 -:1026C00008F410E00F511060E1E0593A08F4E0E03E -:1026D0001855F1E0183A08F0F0E0EF2BF1E0693A14 -:1026E00008F4F0E0BE2FB855E1E0B83A08F0E0E0B9 -:1026F000FE2BA1E0772309F4A0E0E1E0882309F4B0 -:10270000E0E08D2D9C2D60E04CEFF42E2B2F3F2F21 -:102710004A2F5E2F0E9473178E85282F30E040E0ED -:1027200050E060E070E080E090E0E22E01E03D3FAC -:1027300008F400E011E0423E08F410E00F51106090 -:10274000E1E0593A08F4E0E01855F1E0183A08F0F1 -:10275000F0E0EF2BF1E0693A08F4F0E0BE2FB85555 -:10276000E1E0B83A08F0E0E0FE2BA1E0772309F4BD -:10277000A0E0E1E0882309F4E0E08D2D9C2D61E0EC -:102780003CEFF32E2B2F3F2F4A2F5E2F0E94731703 -:102790008A89882311F441E101C042E1CE016FEF43 -:1027A00020E00E940D128E858F8B198E8FEF8B8FFC -:1027B00086E08A8F8E89807F83608E8BCE014596DE -:1027C0006F850E94490ABC01CE010E945011CE01C2 -:1027D0000E948E10DF91CF911F910F91FF90EF908B -:1027E000DF90CF90BF90AF909F908F9008950F9300 -:1027F0001F938C010E946914C80145960E943E0AED -:10280000C801C6960E943E0A1F910F910895411576 -:10281000510529F480917A008F7780937A006A308D -:102820007105B9F063FD02C0E8E001C0E8E2862F5F -:102830008770E82B88E190E00FB6F894A895809314 -:1028400060000FBEE0936000809160008064809320 -:102850006000232BA1F483B7817F846083BFF89449 -:1028600083B7816083BF85B7806685BF8F7D85BF55 -:102870007894889583B78E7F83BF78940EC083B792 -:10288000817F846083BFF89483B7816083BF78942D -:10289000889583B78E7F83BF7894452B29F48091E8 -:1028A0007A00806880937A0008951F920F920FB685 -:1028B0000F9211248F9388E10FB6F89480936000F3 -:1028C000109260000FBE8F910F900FBE0F901F905F -:1028D0001895FC01608341831282138280E2848315 -:1028E0001582168217821086118612861386148628 -:1028F00015860895FC0183810895FF920F931F931D -:102900008C01F62E81E00E94E71880E00E94F0180A -:1029100084E00E94F518F80181816F2D0E94CD207E -:102920001F910F91FF900895EF92FF920F931F93C5 -:10293000CF93DF93EC01162F042FF52EE22E60E0EB -:102940000E947D141770186A1EBD0DB407FEFDCFDE -:10295000802F9F2D9C01F9012E2D213208F020E2BD -:102960008EB508C080818EBD0DB407FEFDCF3196B7 -:102970008EB521502223B1F7CE0161E00E947D1473 -:10298000DF91CF911F910F91FF90EF900895CF931A -:10299000DF93EC0160E00E947D1480E58EBD0DB4F4 -:1029A00007FEFDCF8EB583E78EBD0DB407FEFDCFCC -:1029B0008EB5CE0161E00E947D14DF91CF91089524 -:1029C0001F93CF93DF93EC01162F60E00E947D14DC -:1029D0001EBD0DB407FEFDCF1EB5CE0161E00E9405 -:1029E0007D14812FDF91CF911F9108956FEF0E9489 -:1029F000E014089561EE0E94E014089562EE0E94D2 -:102A0000E01408951F93CF93DF93EC0160E00E94E0 -:102A10007D1480E68EBD0DB407FEFDCF8EB58FEF21 -:102A20008EBD0DB407FEFDCF1EB5CE0161E00E9444 -:102A30007D14113220F0CE010E94FE1410E0812F8F -:102A4000DF91CF911F910895EF92FF920F931F9303 -:102A5000CF93DF93EC01F62EE72E9C81142F941771 -:102A600008F4192F8D81882311F000E002C0092F8E -:102A7000011BCE0160E00E947D1481E68EBD0DB485 -:102A800007FEFDCF8F2D9E2D9C01F901FEB49FEF17 -:102A900007C09EBD0DB407FEFDCF8EB581931150CA -:102AA0001123B9F707C08EBD0DB407FEFDCF9EB54B -:102AB000015001C08FEF0023B1F7CE0161E00E9409 -:102AC0007D148F2DDF91CF911F910F91FF90EF908B -:102AD0000895DF92EF92FF920F931F93CF93DF93AE -:102AE000EC01E62ED72EF22E9C81142F941708F4B9 -:102AF000192F8D81882311F000E002C0092F011BDE -:102B0000CE0160E00E947D14FEBC0DB407FEFDCF37 -:102B10008E2D9D2D9C01F901FEB408C080818EBDD3 -:102B20000DB407FEFDCF31968EB511501123B1F7CC -:102B300006C01EBC0DB407FEFDCF8EB501500023AC -:102B4000C1F7CE0161E00E947D148F2DDF91CF91FE -:102B50001F910F91FF90EF90DF900895CF93DF9337 -:102B6000EC01222311F420EA01C020EBCE010E94E7 -:102B70006915888161E00E94CD20888160E00E9413 -:102B8000CD20DF91CF9108950F931F93CF93DF93C3 -:102B9000EC01162F042F60E00E947D141F7110625B -:102BA0001EBD0DB407FEFDCF1EB50EBD0DB407FE54 -:102BB000FDCF8EB5CE0161E00E947D14812FDF91A3 -:102BC000CF911F910F910895262F4F702295207F4E -:102BD000242B64E0422F0E94C4150895662319F047 -:102BE00061E04FE302C061E040E00E94C415089537 -:102BF0000F931F938C010E942415C80167E040E7E2 -:102C00000E94C4151F910F910895CF93DF93EC019B -:102C10000E94AE15CE010E94F6148073D9F3CE0146 -:102C200067E040E70E94C41584FD02C081E004C053 -:102C3000CE010E94FA1480E0DF91CF910895462FD3 -:102C4000603808F04FE765E00E94C4150895EF92E0 -:102C5000FF920F931F93CF93DF937C01162FEA010E -:102C6000022F60E00E947D141F7110621EBD0DB422 -:102C700007FEFDCF1EB508C088818EBD0DB407FECE -:102C8000FDCF21968EB501500023B1F7C70161E059 -:102C90000E947D14812FDF91CF911F910F91FF90A2 -:102CA000EF900895EF92FF920F931F93DF93CF93CE -:102CB000CDB7DEB728970FB6F894DEBF0FBECDBFF5 -:102CC0007C0109831A832B833C834D835E836F834E -:102CD00078878E010F5F1F4F6AE0A80125E00E94F0 -:102CE0002716C70160E1A80125E00E942716C70149 -:102CF00061E1F70144810E94C41528960FB6F8944B -:102D0000DEBF0FBECDBFCF91DF911F910F91FF901E -:102D1000EF9008951F93CF93DF93EC01162F60E09F -:102D20000E947D141F711EBD0DB407FEFDCF8EB530 -:102D30008FEF8EBD0DB407FEFDCF1EB5CE0161E055 -:102D40000E947D14812FDF91CF911F9108950F93E1 -:102D50001F93CF93DF938C01EB0160E00E948A16F2 -:102D6000482F437F209729F0219711F4486001C034 -:102D70004C60C80160E00E94C415DF91CF911F91A3 -:102D80000F910895FF920F931F93CF93DF93EC0160 -:102D90008B0166E00E948A161A82F7EDFF2EF82258 -:102DA0000230110511F480E206C00130110529F44A -:102DB00081E08A8388E0F82A01C01A82CE0166E0A9 -:102DC0004F2D0E94C415CE0166E00E948A168F1511 -:102DD00011F481E002C01A8280E0DF91CF911F914F -:102DE0000F91FF9008951F93CF93DF93EC01162F5F -:102DF00066E00E948A16143010F04CE003C0412FA8 -:102E0000440F4F5F887F482BCE0166E00E94C415B7 -:102E1000DF91CF911F9108950F931F93CF93DF936D -:102E2000EC01162F042F6730F0F461E00E948A163F -:102E3000282F002351F081E090E002C0880F991FF5 -:102E40001A95E2F7422F482B0AC081E090E002C0B9 -:102E5000880F991F1A95E2F7482F40954223CE011B -:102E600061E00E94C415DF91CF911F910F910895E9 -:102E70000F931F938C010E94C714C8016DE10E943B -:102E80008A16482F4660C8016DE10E94C415C8012A -:102E90006CE10E948A16482F4360C8016CE10E94D1 -:102EA000C4151F910F9108950F931F938C010E94D9 -:102EB000C714C8016DE10E948A16482F4460C801FA -:102EC0006DE10E94C415C8016CE10E948A16482F6A -:102ED0004F63C8016CE10E94C41581E0F80185834D -:102EE0001F910F910895BF92CF92DF92EF92FF92C0 -:102EF0000F931F93DF93CF93CDB7DEB728970FB60D -:102F0000F894DEBF0FBECDBF6C01B62EE982FA8207 -:102F10000B831C832D833E834F835887662389F45C -:102F2000F601E6828A8187838B8180878C81818705 -:102F30008D8182878E8183878F818487888585872D -:102F400007C0F6E0F61708F43DC081E0681761F4A9 -:102F5000EB2DF0E0EA5BFE4FE491C6016E2FAE016F -:102F60004F5F5F4F25E00BC0E62FF0E0EA5BFE4FBE -:102F7000E491C6016E2FAE014F5F5F4F21E00E94CA -:102F800027160B2D10E0F801E45BFE4FE491C6011B -:102F90006E2FF60144810E94C415C60162E00E94B2 -:102FA0008A16005C1E4FF801649121E030E002C0F7 -:102FB000220F331F6A95E2F7482F422BC60162E0C9 -:102FC0000E94C41528960FB6F894DEBF0FBECDBF81 -:102FD000CF91DF911F910F91FF90EF90DF90CF90F5 -:102FE000BF9008950F931F93CF93DF93EC018B0154 -:102FF00067E10E948A1680FF02C080E00DC00115C3 -:10300000110549F0CE010E94F61490E09595879540 -:103010008770F801808381E0DF91CF911F910F913C -:103020000895CF93DF93EC0160E00E948A1681FD42 -:1030300010C0CE0160E00E948A16482F4260CE0187 -:1030400060E00E94C41565E070E080E090E00E94BE -:103050002620DF91CF9108950F931F938C01FC01DF -:10306000808160E00E94CD20C80160E00E948A1645 -:10307000482F4D7FC80160E00E94C4151F910F9139 -:1030800008950F931F938C01FC01808160E00E94E2 -:10309000CD20C8010E94FA14C8010E94FE14C80184 -:1030A00060E00E948A16482F4E7FC80160E00E94AF -:1030B000C4151F910F910895CF93DF93EC010E94E7 -:1030C0001118CE0160E00E948A16482F4160CE019F -:1030D00060E00E94C415CE0167E040E70E94C4157D -:1030E0008E819F81892B9885892B9985892B9A853B -:1030F000892B9B85892B9C85892B9D85892B41F06C -:10310000AE014A5F5F4FCE016AE025E00E942716BC -:10311000CE010E94FE14CE010E94FA14888161E063 -:103120000E94CD20DF91CF910895CF93DF93EC01E2 -:10313000888161E00E948E20898161E00E948E205A -:103140000E940619888160E00E94CD20CE0161E0D6 -:103150000E947D1465E070E080E090E00E942620EF -:10316000CE0165E04FE00E94E415CE0162E070E020 -:103170000E94C216882311F081E08B83CE0160E0AB -:1031800070E00E94C216CE0162E070E00E94A716B5 -:10319000CE0167E040E70E94C415CE016CE40E94B6 -:1031A0001F16CE010E94FE14CE010E94FA14CE0119 -:1031B0000E941118CE0160E00E948A16482F4E7FAF -:1031C000CE0160E00E94C415DF91CF91089588235D -:1031D00019F48CB5806202C08CB58F7D8CBD0895CA -:1031E0009CB5937F982B9CBD08952CB5382F3370D8 -:1031F0002C7F322B3CBD2DB590E09595879595950C -:10320000879581702E7F822B8DBD08958AE061E0C5 -:103210000E94CD208AE061E00E948E208CB5806102 -:103220008CBD8CB580648CBD8DE061E00E948E20E9 -:103230008BE061E00E948E200895FC0185EE99E10B -:10324000918B808B75836483138210828FE190E071 -:10325000928381830895FC01838108956F927F9208 -:103260008F929F92AF92BF92CF92DF92EF92FF9296 -:103270000F931F93CF93DF93FB01EA01998180E0C5 -:10328000288130E0282B392BE081E23231F0E8321E -:1032900021F0E03109F084C04BC04C814F3329F15B -:1032A000403420F44F3109F07BC02FC04F3579F006 -:1032B0004F3709F075C0B901882777FD8095982FA1 -:1032C0000E946A2420E030E040E85DE32EC035959E -:1032D0002795B901882777FD8095982F0E946A2449 -:1032E00020E030E040E05EE320C03595279535953D -:1032F0002795B901882777FD8095982F0E946A2429 -:1033000020E030E040E85EE310C093E0359527957B -:103310009A95E1F7B901882777FD8095982F0E944B -:103320006A2420E030E040E05FE30E941A2532C0CA -:10333000EF8035952795B901882777FD8095982FDF -:103340000E946A2420E030E040E85EE30E946623A9 -:103350003B014C016E2D70E02E81621B71098827A4 -:1033600077FD8095982F0E946A245B016C01FF24F1 -:1033700000E010E0C801B7010E9468249B01AC0185 -:10338000C601B5010E94CF239B01AC01C401B3016A -:103390000E9467239B01AC01832F942F752F00C0DF -:1033A000262F382F492F572FB901CA01DF91CF910E -:1033B0001F910F91FF90EF90DF90CF90BF90AF9053 -:1033C0009F908F907F906F9008950895EF92FF9255 -:1033D0000F931F938C017B01FC01848195810E94D6 -:1033E000E51CF80184819581B7010E94C41CF80195 -:1033F0008481958164EB40E00E947F1CF801848108 -:1034000095810E94FA1BF82EF801848195810E9413 -:10341000E51C80E0FF2009F481E01F910F91FF90EF -:10342000EF9008950F931F938C01FC018481958187 -:103430000E94E51CF801848195810E94BF1CF8015F -:103440008481958164E440810E947F1CF801818120 -:1034500092818F33910551F08F35910561F04F972F -:1034600079F46EE570E080E090E00EC06CEB70E007 -:1034700080E090E009C067E771E080E090E004C080 -:103480006EEE72E080E090E00E9426201F910F9186 -:103490000895CF92DF92EF92FF920F931F938C01CA -:1034A0006B017A01FC01848195810E94E51CF80181 -:1034B00084819581B6010E94C41CF80184819581A4 -:1034C0006EEB40E00E947F1CF801848195810E9490 -:1034D0002E1CF7018083F801848195810E942E1CA7 -:1034E000F7018183F801848195810E942E1CF701E8 -:1034F0008283F801848195810E942E1CF7018383C9 -:10350000F801848195810E942E1CF7018483F801C3 -:10351000848195810E942E1CF7018583F8018481A6 -:1035200095810E942E1CF7018683F8018481958184 -:103530000E942E1CF7018783F801848195810E94E7 -:103540002E1CF7018087F801848195810E94E51C7B -:103550001F910F91FF90EF90DF90CF9008950F9300 -:103560001F938A010E94491AC80168E00E94E91B62 -:1035700020E0F8019085891709F421E0822F1F913E -:103580000F910895CF92DF92EF92FF920F931F93C6 -:10359000DF93CF93CDB7DEB729970FB6F894DEBF90 -:1035A0000FBECDBF8C017B016E010894C11CD11CE4 -:1035B000A6010E94AF1A882329F460E070E08EEF24 -:1035C00092EC05C0C801B701A6010E942E192996E8 -:1035D0000FB6F894DEBF0FBECDBFCF91DF911F9124 -:1035E0000F91FF90EF90DF90CF9008950F931F936E -:1035F0008B01CB0167E00E94E91B20E0F801978175 -:10360000891709F421E0822F1F910F910895EF92FD -:10361000FF920F931F93CF93DF93EC017B01042F55 -:103620008C819D810E94DC1B10E007C0CE01B70198 -:103630000E94F61A8823A9F00AC08C819D81B701E7 -:103640000E94301D882329F0101759F4EFCF81E034 -:1036500001C080E0DF91CF911F910F91FF90EF901B -:1036600008951F5F0117A8F3E8CFEF92FF920F9321 -:103670001F93DF93CF93CDB7DEB728970FB6F8949B -:10368000DEBF0FBECDBF7C01462F8E010F5F1F4FE7 -:10369000B8010E94071BC701B8010E94C21A2896F0 -:1036A0000FB6F894DEBF0FBECDBFCF91DF911F9153 -:1036B0000F91FF90EF9008950E94351B26E636E6A5 -:1036C00046EE5FE30E941A2520E030E040E052E43D -:1036D0000E94672308959F92AF92BF92CF92DF928C -:1036E000EF92FF920F931F93DF93CF93CDB7DEB787 -:1036F00061970FB6F894DEBF0FBECDBF8C01FC0101 -:10370000848195810E94DC1BF80113827E0108945C -:10371000E11CF11CE9E0AE2EB12CAC0EBD1E7FE722 -:10372000C72ED12C992493942DC0C801B7010E94B3 -:10373000F61A882339F1F8018081882341F4C80101 -:10374000B7010E94E619882311F0F8019082C801A0 -:10375000B701A5010E94491A8981803121F4F8013D -:10376000D282C1820BC08D85282F30E0F801818183 -:1037700092818217930714F432832183F8018381A5 -:103780008F5F8383F80184819581B7010E94301D8A -:10379000882359F661960FB6F894DEBF0FBECDBFF1 -:1037A000CF91DF911F910F91FF90EF90DF90CF901D -:1037B000BF90AF909F900895FC01138615861486E4 -:1037C00087E090E012863197009711F00197FACFC9 -:1037D0000895DC0180E00BC0E82FF0E08D9190E0CF -:1037E000E827F927ED5FFC4FE49161508E2F6623A7 -:1037F00099F70895DF92EF92FF920F931F93FC01C8 -:10380000E08001811281F894F80181818E29818301 -:103810008281DE2CD0948D21828383E090E00E940F -:10382000E11FF80181818D2181838AE090E00E946F -:10383000E11FF8010081789485E390E00E94E11F88 -:1038400080E010E0FF240E211F21012B09F081E010 -:103850001F910F91FF90EF90DF900895EF92FF92EC -:103860000F931F93CF93DF937C0101E010E0C0E042 -:10387000D0E0C7010E94FA1B8111102B000F219686 -:10388000C830D105B1F7812FDF91CF911F910F91F2 -:10389000FF90EF9008951F93CF93DF93FC01108169 -:1038A000C181D281912F909560FF12C0F8948A81D6 -:1038B00089238A838981812B89838AE090E00E9411 -:1038C000E11F8A81812B8A83789487E390E011C07D -:1038D000F8948A8189238A838981812B898381E471 -:1038E00090E00E94E11F8A81812B8A83789485E091 -:1038F00090E00E94E11FDF91CF911F910895CF9238 -:10390000DF92EF92FF920F931F93CF93DF938C017F -:10391000E42EFF24F394C0E0D0E0C62EDD2460E066 -:103920008F2D90E08C219D21892B09F061E0C80149 -:103930000E944B1CFF0C2196C830D10581F7EE2068 -:10394000A9F4F894D8011196ED91FC911297918108 -:103950008C918095982391831196ED91FC9112970B -:1039600092818C918095982392837894DF91CF9166 -:103970001F910F91FF90EF90DF90CF9008956CEC26 -:1039800040E00E947F1C0895EF92FF920F931F93D7 -:10399000CF93DF938C017B0165E540E00E947F1CA3 -:1039A000C0E0D0E0F701EC0FFD1FC801608140E0EE -:1039B0000E947F1C2196C830D105A1F7DF91CF91DD -:1039C0001F910F91FF90EF900895DF92EF92FF9279 -:1039D0000F931F93CF93DF93FC010081C181D281AC -:1039E000F8948981D02ED0948D21898378941DE715 -:1039F000E02EFF24115059F182E090E00E94E11F77 -:103A0000888190E08E219F21892BA1F3F8948A81EF -:103A10008D218A838981802B8983789484EF91E03A -:103A20000E94E11FF89489818D21898380E590E0CF -:103A30000E94E11F888110E090E0E822F922EF283F -:103A400009F411E0789484EA91E00E94E11F812F4B -:103A5000DF91CF911F910F91FF90EF90DF9008952C -:103A6000AF92BF92DF92EF92FF920F931F93CF938B -:103A7000DF93EC015B018D85882309F061C0CE01E5 -:103A80000E94E51C882329F41B861D861C8690E075 -:103A90006BC0CE0160EF40E00E947F1C01E0DD249E -:103AA000EE24FF24F394CE010E94FA1B182FCE01BE -:103AB0000E94FA1B113019F48130E1F439C0181753 -:103AC00009F58B85081770F460E0FE01EE0DF11D1D -:103AD000838190E02F2D30E082239323181619065E -:103AE0004CF003C060E0081729F0093008F04CC022 -:103AF0000C874AC0FE01EE0DF11D83818F2983835F -:103B000061E009C0612FFE01EE0DF11D9F2D909522 -:103B1000838189238383CE010E944B1C0F5FFF0C9E -:103B200019F4E394FF24F39487E08E1508F0BBCFDB -:103B3000013430F0DB86DD2011F581E08D871FC078 -:103B40001B861D861C8690E0DE0120E030E0F5013A -:103B5000E20FF31F13968C91139780832F5F3F4FD3 -:103B600011962830310599F7892FDF91CF911F9158 -:103B70000F91FF90EF90DF90BF90AF9008958B81F1 -:103B80008823F1F291E0E0CFD02EBDCFFF920F93CA -:103B90001F938C01F62E862F60E00E948E208F2DC1 -:103BA00090E0FC01EB5CFB4FE491D801EC938F5D5E -:103BB0009B4FFC016491E62FF0E0EE0FFF1FE95EE2 -:103BC000FB4F8591949112969C938E9311971B961F -:103BD0001C921B971D961C921D971C961C92F80117 -:103BE00087E090E012863197009711F00197FACFA5 -:103BF0001F910F91FF9008950F931F93CF93DF9321 -:103C0000BC018230910510F462E070E0E09107039E -:103C1000F091080340E050E0A0E0B0E024C08081D3 -:103C2000918186179707D0F08617970771F48281E4 -:103C30009381109729F013969C938E9312972CC022 -:103C4000909308038093070327C04115510519F08D -:103C50008417950718F48D01AC01EF01DF01828113 -:103C600093819C01F9013097D1F641155105F9F086 -:103C7000CA01861B970B8430910580F48A819B8151 -:103C80000115110521F0F8019383828304C09093FC -:103C9000080380930703FE01329645C0FE01E80F3A -:103CA000F91F619371930297998388833CC0809137 -:103CB000050390910603892B41F480914C0190916A -:103CC0004D01909306038093050340914E0150915E -:103CD0004F014115510541F44DB75EB780914A013E -:103CE00090914B01481B590B20910503309106031D -:103CF00024173507B0F4CA01821B930B8617970768 -:103D000080F0AB014E5F5F4F8417950750F0420F74 -:103D1000531F5093060340930503F9016193719378 -:103D200002C0E0E0F0E0CF01DF91CF911F910F9151 -:103D30000895CF93DF939C01009709F48FC0EC01A5 -:103D400022971B821A826091070370910803611504 -:103D5000710581F488819981820F931F2091050359 -:103D6000309106032817390739F5D0930603C0931D -:103D7000050374C0DB0140E050E0AC17BD0708F15B -:103D8000BB83AA83FE0121913191E20FF31FAE178D -:103D9000BF0779F48D919C911197280F391F2E5FE1 -:103DA0003F4F3983288312968D919C9113979B8363 -:103DB0008A834115510571F4D0930803C09307031A -:103DC0004DC012968D919C911397AD01009711F003 -:103DD000DC01D3CFDA011396DC93CE931297FA016C -:103DE00021913191E20FF31FCE17DF0769F488812B -:103DF0009981280F391F2E5F3F4FFA0131832083AD -:103E00008A819B8193838283E0E0F0E0DB0112965C -:103E10008D919C911397009719F0BC01FD01F6CF8D -:103E2000AB014E5F5F4FDB018D919C91840F951F1D -:103E300020910503309106032817390779F430974C -:103E400029F4109208031092070302C01382128211 -:103E5000425050405093060340930503DF91CF91A9 -:103E600008951F920F920FB60F9211242F933F9334 -:103E70004F935F936F937F938F939F93AF93BF9372 -:103E8000EF93FF9380915B0290915C02892B29F064 -:103E9000E0915B02F0915C020995FF91EF91BF9177 -:103EA000AF919F918F917F916F915F914F913F91D2 -:103EB0002F910F900FBE0F901F9018951F920F9289 -:103EC0000FB60F9211242F933F934F935F936F93ED -:103ED0007F938F939F93AF93BF93EF93FF938091C3 -:103EE0005D0290915E02892B29F0E0915D02F091D4 -:103EF0005E020995FF91EF91BF91AF919F918F91D4 -:103F00007F916F915F914F913F912F910F900FBED5 -:103F10000F901F9018951F920F920FB60F921124B9 -:103F20002F933F938F939F93AF93BF93809163029F -:103F300090916402A0916502B0916602309167028F -:103F40000196A11DB11D232F2D5F2D3720F02D5778 -:103F50000196A11DB11D2093670280936302909387 -:103F60006402A0936502B093660280915F02909113 -:103F70006002A0916102B09162020196A11DB11D83 -:103F800080935F0290936002A0936102B0936202FB -:103F9000BF91AF919F918F913F912F910F900FBE45 -:103FA0000F901F9018958FB7F8942091630230916D -:103FB000640240916502509166028FBFB901CA0147 -:103FC0000895019739F0880F991F880F991F02975C -:103FD0000197F1F70895789484B5826084BD84B523 -:103FE000816084BD85B5826085BD85B5816085BDF4 -:103FF000EEE6F0E0808181608083E1E8F0E010820D -:10400000808182608083808181608083E0E8F0E04D -:10401000808181608083E1EBF0E080818460808337 -:10402000E0EBF0E0808181608083EAE7F0E080816E -:1040300084608083808182608083808181608083CE -:104040008081806880831092C1000895EF92FF9272 -:104050000F931F93CF93DF937B018C013FB7F894AD -:1040600080915F0290916002A0916102B091620222 -:1040700026B5A89B05C02F3F19F00196A11DB11DC3 -:104080003FBFBA2FA92F982F8827820F911DA11DFE -:10409000B11D52E0880F991FAA1FBB1F5A95D1F777 -:1040A000EC0130C00E9465233FB7F89480915F0215 -:1040B00090916002A0916102B091620226B5A89B26 -:1040C00005C02F3F19F00196A11DB11D3FBFBA2FAA -:1040D000A92F982F8827820F911DA11DB11D32E0B5 -:1040E000880F991FAA1FBB1F3A95D1F78C1B9D0BF8 -:1040F000885E9340B8F20894E108F10801091109BB -:10410000C851DC4FE114F1040105110559F6DF91A6 -:10411000CF911F910F91FF90EF900895CF93DF9370 -:10412000482F50E0CA018B5C9B4FFC0134914F5DDE -:104130005B4FFA018491882369F190E0880F991F01 -:10414000FC01ED5FFB4FA591B491FC01E35FFB4FD8 -:10415000C591D491662351F42FB7F8948C91932F85 -:10416000909589238C93888189230BC0623061F4F8 -:104170002FB7F8948C91932F909589238C938881F5 -:10418000832B88832FBF06C09FB7F8948C91832B15 -:104190008C939FBFDF91CF910895482F50E0CA01C3 -:1041A000875B9B4FFC012491CA018B5C9B4FFC01F8 -:1041B00094914F5D5B4FFA013491332309F440C071 -:1041C000222351F1233071F0243028F42130A1F062 -:1041D000223011F514C02630B1F02730C1F0243060 -:1041E000D9F404C0809180008F7703C08091800053 -:1041F0008F7D8093800010C084B58F7702C084B516 -:104200008F7D84BD09C08091B0008F7703C08091FD -:10421000B0008F7D8093B000E32FF0E0EE0FFF1F22 -:10422000E35FFB4FA591B4912FB7F894662321F477 -:104230008C919095892302C08C91892B8C932FBFF0 -:104240000895DC015C968C915C97FD01E80FF11DEF -:10425000E35AFF4F20815C968C915C9790E0019629 -:104260008F7390705C968C935C975696ED91FC9151 -:10427000579720835096ED91FC91519780818064EF -:1042800080835B969C915B975C968C915C9798176A -:1042900039F45296ED91FC91539780818F7D808304 -:1042A0000895DF92EF92FF920F931F93CF93DF93C6 -:1042B000EC017A018B01D22EE889F98982E08083B2 -:1042C000403081EE580780E0680780E07807A1F071 -:1042D00060E079E08DE390E0A80197010E947D25E0 -:1042E000215030404040504056954795379527958E -:1042F00080E12030380798F0E889F989108260E879 -:1043000074E88EE190E0A80197010E947D2521507C -:104310003040404050405695479537952795EC855D -:10432000FD853083EE85FF852083188EEC89FD891D -:10433000D082EA89FB89808180618083EA89FB8958 -:10434000808188608083EA89FB898081806880839E -:10435000EA89FB8980818F7D8083DF91CF911F91D6 -:104360000F91FF90EF90DF900895FC01218D828DD9 -:1043700030E0205C3F4F281B31092F733070C9019A -:104380000895FC01918D828D981719F42FEF3FEF5E -:1043900006C0828DE80FF11D858D282F30E0C90100 -:1043A0000895DC0159969C9159975A968C915A9789 -:1043B000981719F42FEF3FEF10C05A968C915A9727 -:1043C000FD01E80FF11D958D5A968C915A978F5FDC -:1043D0008F735A968C93292F30E0C9010895CF939B -:1043E000DF93EC01888D882361F419C08C9185FFDF -:1043F0000AC0E889F989808185FF05C0CE010E9445 -:104400002121AA89BB898C9185FD05C0E889F9899C -:10441000808186FD04C00FB607FEE8CFF4CFDF91A0 -:10442000CF9108950F931F93CF93DF93EC01062F45 -:104430009B8D8C8D981791F5E889F989808185FF8E -:104440002DC0EE89FF896083E889F98980818064C5 -:1044500080831DC00FB607FC08C0E889F9898081F8 -:1044600085FF03C0CE010E9421218C8D181791F386 -:104470008B8DFE01E80FF11DE35AFF4F00831B8F68 -:10448000EA89FB8980818062808381E0888F81E076 -:1044900090E0DF91CF911F910F9108951B8D1F5FC9 -:1044A0001F73E3CF8AED92E2892B51F080E090E018 -:1044B000892B31F00E94DA22882311F00E9400003B -:1044C00008951F920F920FB60F9211242F938F937E -:1044D0009F93EF93FF93E0917802F09179028081AE -:1044E00082FD16C0E0917E02F0917F0220819091C2 -:1044F00081029F5F9F7380918202981771F0E09113 -:104500008102F0E0E859FD4F258F9093810205C0AC -:10451000E0917E02F0917F02E081FF91EF919F9107 -:104520008F912F910F900FBE0F901F9018951092A2 -:104530006B0210926A0288EE93E0A0E0B0E08093F4 -:104540006C0290936D02A0936E02B0936F0284E5AB -:1045500091E0909369028093680285EC90E09093DB -:1045600075028093740284EC90E0909377028093BC -:10457000760280EC90E0909379028093780281EC4F -:1045800090E090937B0280937A0282EC90E090938B -:104590007D0280937C0286EC90E090937F02809372 -:1045A0007E02109281021092820210928302109277 -:1045B0008402089588E692E00E94B52120E0892BCC -:1045C00009F021E0822F08951F920F920FB60F92EB -:1045D00011242F933F934F935F936F937F938F9308 -:1045E0009F93AF93BF93EF93FF9388E692E00E946F -:1045F0002121FF91EF91BF91AF919F918F917F9179 -:104600006F915F914F913F912F910F900FBE0F903F -:104610001F901895CF93DF930E94EB1F0E94F20921 -:10462000C2E5D2E20E945B092097E1F30E94522288 -:10463000F9CF0E94FC1D0895CF92DF92EF92FF9276 -:104640000F931F93CF93DF937C016B018A01C0E02E -:10465000D0E00FC0D6016D916D01D701ED91FC91B5 -:104660000190F081E02DC7010995C80FD91F0150B5 -:1046700010400115110571F7CE01DF91CF911F9107 -:104680000F91FF90EF90DF90CF900895CF93DF933D -:10469000EC016115710519F420E030E00FC0DB0179 -:1046A0000D900020E9F71197A61BB70BE881F9815F -:1046B0000280F381E02DAD0109959C01C901DF91D4 -:1046C000CF9108950E944623089508955058BB271E -:1046D000AA270ED075C166D130F06BD120F031F42D -:1046E0009F3F11F41EF45BC10EF4E095E7FB51C14E -:1046F000E92F77D180F3BA1762077307840795070C -:1047000018F071F49EF58FC10EF4E0950B2EBA2FC0 -:10471000A02D0B01B90190010C01CA01A0011124C7 -:10472000FF27591B99F0593F50F4503E68F11A1673 -:10473000F040A22F232F342F4427585FF3CF469504 -:1047400037952795A795F0405395C9F77EF41F1626 -:10475000BA0B620B730B840BBAF09150A1F0FF0FF0 -:10476000BB1F661F771F881FC2F70EC0BA0F621FDC -:10477000731F841F48F4879577956795B795F795CC -:104780009E3F08F0B3CF9395880F08F09927EE0F5E -:10479000979587950895D9D008F481E008950CD0B5 -:1047A0000FC107D140F0FED030F021F45F3F19F087 -:1047B000F0C0511139C1F3C014D198F39923C9F352 -:1047C0005523B1F3951B550BBB27AA276217730717 -:1047D000840738F09F5F5F4F220F331F441FAA1FCB -:1047E000A9F333D00E2E3AF0E0E830D0915050408B -:1047F000E695001CCAF729D0FE2F27D0660F771F39 -:10480000881FBB1F261737074807AB07B0E809F01A -:10481000BB0B802DBF01FF2793585F4F2AF09E3FAF -:10482000510568F0B6C000C15F3FECF3983EDCF381 -:10483000869577956795B795F7959F5FC9F7880F28 -:10484000911D9695879597F90895E1E0660F771F7A -:10485000881FBB1F621773078407BA0720F0621B0B -:10486000730B840BBA0BEE1F88F7E095089504D004 -:104870006894B111D9C00895BCD088F09F5790F0CA -:10488000B92F9927B751A0F0D1F0660F771F881F75 -:10489000991F1AF0BA95C9F712C0B13081F0C3D090 -:1048A000B1E00895C0C0672F782F8827B85F39F02E -:1048B000B93FCCF3869577956795B395D9F73EF4D4 -:1048C00090958095709561957F4F8F4F9F4F08957C -:1048D000E89409C097FB3EF490958095709561959A -:1048E0007F4F8F4F9F4F9923A9F0F92F96E9BB2750 -:1048F0009395F695879577956795B795F111F8CFCC -:10490000FAF4BB0F11F460FF1BC06F5F7F4F8F4F36 -:104910009F4F16C0882311F096E911C0772321F02C -:104920009EE8872F762F05C0662371F096E8862FC4 -:1049300070E060E02AF09A95660F771F881FDAF71B -:10494000880F9695879597F90895990F0008550F48 -:10495000AA0BE0E8FEEF16161706E807F907C0F005 -:1049600012161306E407F50798F0621B730B840B0D -:10497000950B39F40A2661F0232B242B252B21F4E7 -:1049800008950A2609F4A140A6958FEF811D811D87 -:10499000089597F99F6780E870E060E008959FEFC1 -:1049A00080EC089500240A941616170618060906C6 -:1049B000089500240A941216130614060506089595 -:1049C000092E0394000C11F4882352F0BB0F40F41D -:1049D000BF2B11F460FF04C06F5F7F4F8F4F9F4F5D -:1049E000089557FD9058440F551F59F05F3F71F0DF -:1049F0004795880F97FB991F61F09F3F79F0879546 -:104A00000895121613061406551FF2CF4695F1DFCE -:104A100008C0161617061806991FF1CF869571055E -:104A2000610508940895E894BB2766277727CB0192 -:104A300097F908950BD0C4CFB5DF28F0BADF18F08E -:104A4000952309F0A6CFABCF1124EECFCADFA0F398 -:104A5000959FD1F3950F50E0551F629FF001729F13 -:104A6000BB27F00DB11D639FAA27F00DB11DAA1F32 -:104A7000649F6627B00DA11D661F829F2227B00D7F -:104A8000A11D621F739FB00DA11D621F839FA00D0A -:104A9000611D221F749F3327A00D611D231F849F5A -:104AA000600D211D822F762F6A2F11249F575040B1 -:104AB0008AF0E1F088234AF0EE0FFF1FBB1F661F4C -:104AC000771F881F91505040A9F79E3F510570F005 -:104AD00060CFAACF5F3FECF3983EDCF386957795E5 -:104AE0006795B795F795E7959F5FC1F7FE2B880F00 -:104AF000911D9695879597F90895A1E21A2EAA1B04 -:104B0000BB1BFD010DC0AA1FBB1FEE1FFF1FA2177D -:104B1000B307E407F50720F0A21BB30BE40BF50B7A -:104B2000661F771F881F991F1A9469F76095709503 -:104B3000809590959B01AC01BD01CF010895EE0FCA -:104B4000FF1F0590F491E02D0994AA1BBB1B51E1B6 -:104B500007C0AA1FBB1FA617B70710F0A61BB70BED -:104B6000881F991F5A95A9F780959095BC01CD0192 -:104B700008952F923F924F925F926F927F928F9201 -:104B80009F92AF92BF92CF92DF92EF92FF920F93DC -:104B90001F93CF93DF93CDB7DEB7CA1BDB0B0FB6E6 -:104BA000F894DEBF0FBECDBF09942A8839884888A3 -:104BB0005F846E847D848C849B84AA84B984C88439 -:104BC000DF80EE80FD800C811B81AA81B981CE0F30 -:104BD000D11D0FB6F894DEBF0FBECDBFED01089515 -:044BE000F894FFCF77 -:104BE40054656D70657261747572652053656E737A -:104BF4006F7200312E30006661696C006F6B0000CB -:104C0400312E346231202831383834386132290069 -:104C140073656E736F72007265706561746572009E -:104C240030750000307500000100800009030000A9 -:104C34000000000012221C23B521D121C121EF2143 -:00000001FF diff --git a/NodeJsController/DallasTemperatureSensor/DallasTemperatureSensor.ino b/NodeJsController/DallasTemperatureSensor/DallasTemperatureSensor.ino deleted file mode 100644 index 3ac3888..0000000 --- a/NodeJsController/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ /dev/null @@ -1,69 +0,0 @@ -// Example sketch showing how to send in OneWire temperature readings -#include -#include -#include -#include - -#define ONE_WIRE_BUS 3 // Pin where dallase sensor is connected -#define MAX_ATTACHED_DS18B20 16 -unsigned long WAIT_TIME = 30000; // Wait for feedback from controller after sending and before going to sleep (in milliseconds) -unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) -OneWire oneWire(ONE_WIRE_BUS); -DallasTemperature sensors(&oneWire); -MySensor gw; -float lastTemperature[MAX_ATTACHED_DS18B20]; -int numSensors=0; -boolean receivedConfig = false; -boolean metric = true; -// Initialize temperature message -MyMessage msg(0,V_TEMP); - -void setup() -{ - // Startup OneWire - sensors.begin(); - - // Startup and initialize MySensors library. Set callback for incoming messages. - gw.begin(); - - // Send the sketch version information to the gateway and Controller - gw.sendSketchInfo("Temperature Sensor", "1.0"); - - // Fetch the number of attached temperature sensors - numSensors = sensors.getDeviceCount(); - - // Present all sensors to controller - for (int i=0; i(static_cast((gw.getConfig().isMetric?sensors.getTempCByIndex(i):sensors.getTempFByIndex(i)) * 10.)) / 10.; - - // Only send data if temperature has changed and no error - if (lastTemperature[i] != temperature && temperature != -127.00) { - - // Send in the new temperature - gw.send(msg.setSensor(i).set(temperature,1)); - lastTemperature[i]=temperature; - } - } - delay(WAIT_TIME); - gw.process(); - gw.sleep(SLEEP_TIME); -} - - diff --git a/NodeJsController/NodeJsController.js b/NodeJsController/NodeJsController.js index 6c52630..53639a2 100644 --- a/NodeJsController/NodeJsController.js +++ b/NodeJsController/NodeJsController.js @@ -11,8 +11,8 @@ const dbAddress = '127.0.0.1'; const dbPort = 27017; const dbName = 'MySensorsDb'; -const fwHexFiles = [ 'BlinkRed.hex', 'BlinkGreen.hex', 'DallasTemperatureSensor.cpp.hex' ]; -const fwDefaultType = 2; // index of hex file from array above +const fwHexFiles = [ ]; +const fwDefaultType = 0xFFFF; // index of hex file from array above (0xFFFF == none defined) const FIRMWARE_BLOCK_SIZE = 16; const BROADCAST_ADDRESS = 255; diff --git a/NodeJsController/Readme.html b/NodeJsController/Readme.md similarity index 91% rename from NodeJsController/Readme.html rename to NodeJsController/Readme.md index 6766851..98dee49 100644 --- a/NodeJsController/Readme.html +++ b/NodeJsController/Readme.md @@ -1,5 +1,4 @@

MySensors with NodeJS Controller and OTA bootloader on RPi

-

My RPi runs Arduino to compile and flash sketches and the bootloader. With this setup no separate PC/Mac is needed. Exactly the same could be achieved (faster) using a PC/Mac for all the Arduino compilation and flashing activities – just skip the steps and execute on PC/Mac instead.

Hardware

Headless Raspberry Pi model B with wired Ethernet

I'm connecting a monitor only for first time boot to get the IP address and then connect via Putty/xRDP

@@ -140,8 +139,6 @@ export PATH

  • git checkout development
  • cd NodeJsController
  • npm install -
  • nano NodeJsController.js (optional : removing sample firmwares) -

    const fwHexFiles = [ ];

  • to confirm that the NodeJsController is working as expected and connects to the local mongo DB: "node NodeJsController.js" which should start the controller, connect to the database and run into an error connecting to the gateway. Stop node again via Ctrl-c

    Start NodeJsController on boot

    @@ -215,7 +212,7 @@ Arduino RESET <-> Raspberry Pi GPIO22 (pin 15)

    //const gwType = 'Serial';
    //const gwPort = '/dev/ttyAMA0';
    //const gwBaud = 115200;

    -
  • sudo service mysensors restart +
  • sudo service mysensors restart (at this point stop/restart doesn't work. use "sudo killall node" followed by "sudo service mysensors start" instead)

    Ethernet Gateway

    @@ -262,7 +259,7 @@ IPAddress myIp (10, 0, 1, 99);

    • nano ~/Arduino/NodeJsController/NodeJsController.js

      const gwAddress = '10.0.1.99';

      -
    • sudo service mysensors restart +
    • sudo service mysensors restart (at this point stop/restart doesn't work. use "sudo killall node" followed by "sudo service mysensors start" instead)

    Sensor Node Bootloader

    @@ -291,12 +288,14 @@ ISP_MCU = m328p

    End-to-End Test

    -

    Add Firmware to Controller

    +

    Add Firmware to Controller (here: DallasTemperatureSensor)

      +
    • use Arduino IDE or codebender or whatever other way to compile your sketch +
    • copy the compiled DallasTemperatureSensor.cpp.hex file to the NodeJsController directory (if using the Arduino IDE, enable verbose logging in preferences and then watch the compilation process to find the temp directory where the output is stored)
    • nano ~/Arduino/NodeJsController/NodeJsController.js -

      const fwHexFiles = [ 'DallasTemperatureSensor.cpp.hex' ];
      -const fwDefaultType = 0;

      -
    • sudo service mysensors restart +

      const fwHexFiles = [ 'DallasTemperatureSensor.cpp.hex' ];
      +const fwDefaultType = 0;

      +
    • sudo service mysensors restart (at this point stop/restart doesn't work. use "sudo killall node" followed by "sudo service mysensors start" instead)

    Flash Firmware OTA

      @@ -305,5 +304,5 @@ const fwDefaultType = 0;

    Check functionality

      -
    • in addition to watching the log file (tail command above) you can connect to the mongo db using a client (e.g. Robomongo) and check if new values are written to the database as a real end-to-end test +
    • in addition to watching the log file (tail command above) you can connect to the mongo db using a client (e.g. Robomongo) and check if new values are written to the database as a real end-to-end test once the bootloader finished uploading the firmware
    From cd84e410fa2dd38acd4334840d38748cb695aeb2 Mon Sep 17 00:00:00 2001 From: ToSa27 Date: Mon, 25 Aug 2014 17:38:25 +0200 Subject: [PATCH 002/137] use codebender to compile sketches I had codebender username/password included originally but compiling works without. Codebender usage guidelines allow "usage via API". --- NodeJsController/NodeJsController.js | 179 +++++++++++++++------------ NodeJsController/package.json | 1 + 2 files changed, 103 insertions(+), 77 deletions(-) diff --git a/NodeJsController/NodeJsController.js b/NodeJsController/NodeJsController.js index 53639a2..fbe1470 100644 --- a/NodeJsController/NodeJsController.js +++ b/NodeJsController/NodeJsController.js @@ -1,18 +1,18 @@ -const gwType = 'Ethernet'; -const gwAddress = '10.0.1.99'; -const gwPort = 9999; +//const gwType = 'Ethernet'; +//const gwAddress = '10.0.1.99'; +//const gwPort = 9999; -//const gwType = 'Serial'; +const gwType = 'Serial'; //const gwPort = 'COM4'; -//const gwPort = '/dev/ttyUSB0'; -//const gwBaud = 115200; +const gwPort = '/dev/ttyAMA0'; +const gwBaud = 115200; const dbAddress = '127.0.0.1'; const dbPort = 27017; const dbName = 'MySensorsDb'; -const fwHexFiles = [ ]; -const fwDefaultType = 0xFFFF; // index of hex file from array above (0xFFFF == none defined) +const fwSketches = [ '../libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino' ]; +const fwDefaultType = 0; // index of hex file from array above const FIRMWARE_BLOCK_SIZE = 16; const BROADCAST_ADDRESS = 255; @@ -117,6 +117,8 @@ const P_ULONG32 = 5; const P_CUSTOM = 6; var fs = require('fs'); +var path = require('path'); +var requestify = require('requestify'); var appendedString=""; function crcUpdate(old, value) { @@ -146,76 +148,99 @@ function pushDWord(arr, val) { arr.push((val >> 24) & 0x000000FF); } -function loadFirmware(fwtype, fwversion, filename, db) { - console.log("loading firmware: " + filename); - fwdata = []; - var start = 0; - var end = 0; - var pos = 0; - var hex = fs.readFileSync(filename).toString().split("\n"); - for(l in hex) { - line = hex[l].trim(); - if (line.length > 0) { - while (line.substring(0, 1) != ":") - line = line.substring(1); - var reclen = parseInt(line.substring(1, 3), 16); - var offset = parseInt(line.substring(3, 7), 16); - var rectype = parseInt(line.substring(7, 9), 16); - var data = line.substring(9, 9 + 2 * reclen); - var chksum = parseInt(line.substring(9 + (2 * reclen), 9 + (2 * reclen) + 2), 16); - if (rectype == 0) { - if ((start == 0) && (end == 0)) { - if (offset % 128 > 0) - throw new Error("error loading hex file - offset can't be devided by 128"); - start = offset; - end = offset; +function loadFirmware(fwtype, fwversion, sketch, db) { + var filename = path.basename(sketch); + console.log("compiling firmware: " + filename); + var req = { + files: [{ + filename: filename, + content: fs.readFileSync(sketch).toString() + }], + format: "hex", + version: "105", + build: { + mcu: "atmega328p", + f_cpu: "16000000L", + core: "arduino", + variant: "standard" + } + }; + requestify.post('https://codebender.cc/utilities/compile/', req).then(function(res) { + var body = JSON.parse(res.getBody()); + if (body.success) { + console.log("loading firmware: " + filename); + fwdata = []; + var start = 0; + var end = 0; + var pos = 0; + var hex = body.output.split("\n"); + for(l in hex) { + line = hex[l].trim(); + if (line.length > 0) { + while (line.substring(0, 1) != ":") + line = line.substring(1); + var reclen = parseInt(line.substring(1, 3), 16); + var offset = parseInt(line.substring(3, 7), 16); + var rectype = parseInt(line.substring(7, 9), 16); + var data = line.substring(9, 9 + 2 * reclen); + var chksum = parseInt(line.substring(9 + (2 * reclen), 9 + (2 * reclen) + 2), 16); + if (rectype == 0) { + if ((start == 0) && (end == 0)) { + if (offset % 128 > 0) + throw new Error("error loading hex file - offset can't be devided by 128"); + start = offset; + end = offset; + } + if (offset < end) + throw new Error("error loading hex file - offset lower than end"); + while (offset > end) { + fwdata.push(255); + pos++; + end++; + } + for (var i = 0; i < reclen; i++) { + fwdata.push(parseInt(data.substring(i * 2, (i * 2) + 2), 16)); + pos++; + } + end += reclen; + } } - if (offset < end) - throw new Error("error loading hex file - offset lower than end"); - while (offset > end) { - fwdata.push(255); - pos++; - end++; - } - for (var i = 0; i < reclen; i++) { - fwdata.push(parseInt(data.substring(i * 2, (i * 2) + 2), 16)); - pos++; - } - end += reclen; + } + var pad = end % 128; // ATMega328 has 64 words per page / 128 bytes per page + for (var i = 0; i < 128 - pad; i++) { + fwdata.push(255); + pos++; + end++; } - } - } - var pad = end % 128; // ATMega328 has 64 words per page / 128 bytes per page - for (var i = 0; i < 128 - pad; i++) { - fwdata.push(255); - pos++; - end++; - } - var blocks = (end - start) / FIRMWARE_BLOCK_SIZE; - var crc = 0xFFFF; - for (var i = 0; i < blocks * FIRMWARE_BLOCK_SIZE; ++i) { - var v = crc; - crc = crcUpdate(crc, fwdata[i]); - } - db.collection('firmware', function(err, c) { - c.update({ - 'type': fwtype, - 'version': fwversion - }, { - $set: { - 'filename': filename, - 'blocks': blocks, - 'crc': crc, - 'data': fwdata + var blocks = (end - start) / FIRMWARE_BLOCK_SIZE; + var crc = 0xFFFF; + for (var i = 0; i < blocks * FIRMWARE_BLOCK_SIZE; ++i) { + var v = crc; + crc = crcUpdate(crc, fwdata[i]); } - }, { - upsert: true - }, function(err, result) { - if (err) - console.log('Error writing firmware to database'); - }); - }); - console.log("loading firmware done. blocks: " + blocks + " / crc: " + crc); + db.collection('firmware', function(err, c) { + c.update({ + 'type': fwtype, + 'version': fwversion + }, { + $set: { + 'filename': filename, + 'blocks': blocks, + 'crc': crc, + 'data': fwdata + } + }, { + upsert: true + }, function(err, result) { + if (err) + console.log('Error writing firmware to database'); + }); + }); + console.log("loading firmware done. blocks: " + blocks + " / crc: " + crc); + } else { + console.log("error: %j", res.body); + } + }); } /* @@ -645,8 +670,8 @@ dbc.connect('mongodb://' + dbAddress + ':' + dbPort + '/' + dbName, function(err db.createCollection('firmware', function(err, collection) { }); // ToDo : check for new hex files / only load if new / get type and version from filename - for (var i = 0; i < fwHexFiles.length; i++) - loadFirmware(i, 1, fwHexFiles[i], db); + for (var i = 0; i < fwSketches.length; i++) + loadFirmware(i, 1, fwSketches[i], db); var gw; if (gwType == 'Ethernet') { diff --git a/NodeJsController/package.json b/NodeJsController/package.json index a4866a6..eaffa4a 100644 --- a/NodeJsController/package.json +++ b/NodeJsController/package.json @@ -5,6 +5,7 @@ "dependencies": { "mongodb": "~1.4.7", "net": "~1.0.2", + "requestify": "^0.1.16", "serialport": "^1.4.5" } } From 1dbe7497bdfb47e043402ae77036f9df26de5732 Mon Sep 17 00:00:00 2001 From: ToSa27 Date: Mon, 25 Aug 2014 18:34:51 +0200 Subject: [PATCH 003/137] Added technical details for controller developers regarding OTA bootloader --- Bootloader/Readme.md | 48 +++++++++++++++++++++++++++- NodeJsController/NodeJsController.js | 4 +-- NodeJsController/Readme.md | 4 +-- 3 files changed, 50 insertions(+), 6 deletions(-) diff --git a/Bootloader/Readme.md b/Bootloader/Readme.md index 810b16a..b6d7e33 100644 --- a/Bootloader/Readme.md +++ b/Bootloader/Readme.md @@ -1 +1,47 @@ -See NodeJsController/Readme.md for usage instructions... \ No newline at end of file +See NodeJsController/Readme.md for usage instructions... + +

    Technical details to write your own controller

    +All initialization the bootloader does (finding parent / requesting nodeId on first start) uses the same packets as a normal MySensors sketch. There is no need for the controller to distinguish between packets from the bootloader and packets from normal sketch execution. The controller only needs to care about two additional request/response communications. All communication is binary. +

    FirmwareConfig

    +
      +
    • the bootloader sends a FirmwareConfigRequest packet to the gateway to request information about the firmware it should execute: +

      +typedef struct
      +{
      + uint16_t type;
      + uint16_t version;
      +} FirmwareConfigRequest; +

      +
    • the gateway (the controller) responds with a FirmwareConfigResponse including details about the firmware the sensor should execute: +

      +typedef struct
      +{
      + uint16_t type;
      + uint16_t version;
      + uint16_t blocks;
      + uint16_t crc;
      +} FirmwareConfigResponse; +

      +
    +

    Firmware

    +
      +
    • the bootloader sends a FirmwareRequest packet to the gateway to request a specific subset (block) of the compiled firmware: +

      +typedef struct
      +{
      + uint16_t type;
      + uint16_t version;
      + uint16_t block;
      +} FirmwareRequest; +

      +
    • the gateway (the controller) responds with a FirmwareResponse including the specific block of the compiled firmware: +
    +

    +typedef struct
    +{
    + uint16_t type;
    + uint16_t version;
    + uint16_t block;
    + uint8_t data[FIRMWARE_BLOCK_SIZE];
    +} FirmwareResponse; +

    diff --git a/NodeJsController/NodeJsController.js b/NodeJsController/NodeJsController.js index fbe1470..8bb67da 100644 --- a/NodeJsController/NodeJsController.js +++ b/NodeJsController/NodeJsController.js @@ -11,8 +11,8 @@ const dbAddress = '127.0.0.1'; const dbPort = 27017; const dbName = 'MySensorsDb'; -const fwSketches = [ '../libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino' ]; -const fwDefaultType = 0; // index of hex file from array above +const fwSketches = [ ]; +const fwDefaultType = 0xFFFF; // index of hex file from array above (0xFFFF const FIRMWARE_BLOCK_SIZE = 16; const BROADCAST_ADDRESS = 255; diff --git a/NodeJsController/Readme.md b/NodeJsController/Readme.md index 98dee49..d8b364b 100644 --- a/NodeJsController/Readme.md +++ b/NodeJsController/Readme.md @@ -290,10 +290,8 @@ ISP_MCU = m328p

    End-to-End Test

    Add Firmware to Controller (here: DallasTemperatureSensor)

      -
    • use Arduino IDE or codebender or whatever other way to compile your sketch -
    • copy the compiled DallasTemperatureSensor.cpp.hex file to the NodeJsController directory (if using the Arduino IDE, enable verbose logging in preferences and then watch the compilation process to find the temp directory where the output is stored)
    • nano ~/Arduino/NodeJsController/NodeJsController.js -

      const fwHexFiles = [ 'DallasTemperatureSensor.cpp.hex' ];
      +

      const fwHexFiles = [ '../libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino' ];
      const fwDefaultType = 0;

    • sudo service mysensors restart (at this point stop/restart doesn't work. use "sudo killall node" followed by "sudo service mysensors start" instead)
    From 724567e295236436fb84e55f6adfc486c6360072 Mon Sep 17 00:00:00 2001 From: Daniel Wiegert Date: Wed, 27 Aug 2014 15:24:04 +0200 Subject: [PATCH 004/137] Bugfixes and rewrite parts of code --- libraries/MySensors/MyMQTT.cpp | 364 +++++++++--------- libraries/MySensors/MyMQTT.h | 29 +- .../examples/MQTTGateway/MQTTGateway.ino | 79 ++-- 3 files changed, 215 insertions(+), 257 deletions(-) mode change 100644 => 100755 libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino diff --git a/libraries/MySensors/MyMQTT.cpp b/libraries/MySensors/MyMQTT.cpp index 0884906..2ab42b5 100755 --- a/libraries/MySensors/MyMQTT.cpp +++ b/libraries/MySensors/MyMQTT.cpp @@ -12,71 +12,89 @@ version 2 as published by the Free Software Foundation. #include "MyMQTT.h" #include "utility/MsTimer2.h" +char V_0[] PROGMEM = "TEMP"; //V_TEMP +char V_1[] PROGMEM = "HUM"; //V_HUM +char V_2[] PROGMEM = "LIGHT"; //V_LIGHT +char V_3[] PROGMEM = "DIMMER"; //V_DIMMER +char V_4[] PROGMEM = "PRESSURE"; //V_PRESSURE +char V_5[] PROGMEM = "FORECAST"; //V_FORECAST +char V_6[] PROGMEM = "RAIN"; //V_RAIN +char V_7[] PROGMEM = "RAINRATE"; //V_RAINRATE +char V_8[] PROGMEM = "WIND"; //V_WIND +char V_9[] PROGMEM = "GUST"; //V_GUST +char V_10[] PROGMEM = "DIRECTON"; //V_DIRECTON +char V_11[] PROGMEM = "UV"; //V_UV +char V_12[] PROGMEM = "WEIGHT"; //V_WEIGHT +char V_13[] PROGMEM = "DISTANCE"; //V_DISTANCE +char V_14[] PROGMEM = "IMPEDANCE"; //V_IMPEDANCE +char V_15[] PROGMEM = "ARMED"; //V_ARMED +char V_16[] PROGMEM = "TRIPPED"; //V_TRIPPED +char V_17[] PROGMEM = "WATT"; //V_WATT +char V_18[] PROGMEM = "KWH"; //V_KWH +char V_19[] PROGMEM = "SCENE_ON"; //V_SCENE_ON +char V_20[] PROGMEM = "SCENE_OFF"; //V_SCENE_OFF +char V_21[] PROGMEM = "HEATER"; //V_HEATER +char V_22[] PROGMEM = "HEATER_SW"; //V_HEATER_SW +char V_23[] PROGMEM = "LIGHT_LEVEL"; //V_LIGHT_LEVEL +char V_24[] PROGMEM = "VAR1"; //V_VAR1 +char V_25[] PROGMEM = "VAR2"; //V_VAR2 +char V_26[] PROGMEM = "VAR3"; //V_VAR3 +char V_27[] PROGMEM = "VAR4"; //V_VAR4 +char V_28[] PROGMEM = "VAR5"; //V_VAR5 +char V_29[] PROGMEM = "UP"; //V_UP +char V_30[] PROGMEM = "DOWN"; //V_DOWN +char V_31[] PROGMEM = "STOP"; //V_STOP +char V_32[] PROGMEM = "IR_SEND"; //V_IR_SEND +char V_33[] PROGMEM = "IR_RECEIVE"; //V_IR_RECEIVE +char V_34[] PROGMEM = "FLOW"; //V_FLOW +char V_35[] PROGMEM = "VOLUME"; //V_VOLUME +char V_36[] PROGMEM = "LOCK_STATUS"; //V_LOCK_STATUS +char V_37[] PROGMEM = "DUST_LEVEL"; //V_DUST_LEVEL +char V_38[] PROGMEM = "VOLTAGE"; //V_VOLTAGE +char V_39[] PROGMEM = "CURRENT"; //V_CURRENT +char V_40[] PROGMEM = ""; // +char V_41[] PROGMEM = ""; // +char V_42[] PROGMEM = ""; // +char V_43[] PROGMEM = ""; // +char V_44[] PROGMEM = ""; // +char V_45[] PROGMEM = ""; // +char V_46[] PROGMEM = ""; // +char V_47[] PROGMEM = ""; // +char V_48[] PROGMEM = ""; // +char V_49[] PROGMEM = ""; // +char V_50[] PROGMEM = ""; // +char V_51[] PROGMEM = ""; // +char V_52[] PROGMEM = ""; // +char V_53[] PROGMEM = ""; // +char V_54[] PROGMEM = ""; // +char V_55[] PROGMEM = ""; // +char V_56[] PROGMEM = ""; // +char V_57[] PROGMEM = ""; // +char V_58[] PROGMEM = ""; // +char V_59[] PROGMEM = ""; // +char V_60[] PROGMEM = "Started!\n"; //Custom for MQTTGateway +char V_61[] PROGMEM = "SKETCH_NAME"; //Custom for MQTTGateway +char V_62[] PROGMEM = "SKETCH_VERSION"; //Custom for MQTTGateway +char V_63[] PROGMEM = "UNKNOWN"; //Custom for MQTTGateway + +////////////////////////////////////////////////////////////////// + +PROGMEM const char *vType[] = { + V_0, V_1, V_2, V_3, V_4, V_5, V_6, V_7, V_8, V_9, V_10, + V_11, V_12, V_13, V_14, V_15, V_16, V_17, V_18, V_19, V_20, + V_21, V_22, V_23, V_24, V_25, V_26, V_27, V_28, V_29, V_30, + V_31, V_32, V_33, V_34, V_35, V_36, V_37, V_38, V_39, V_40, + V_41, V_42, V_43, V_44, V_45, V_46, V_47, V_48, V_49, V_50, + V_51, V_52, V_53, V_54, V_55, V_56, V_57, V_58, V_59, V_60, + V_61, V_62, V_63 +}; char broker[] PROGMEM = MQTT_BROKER_PREFIX; -char S_0[] PROGMEM = "Temperature"; //V_TEMP -char S_1[] PROGMEM = "Humidity"; //V_HUM -char S_2[] PROGMEM = "Light"; //V_LIGHT -char S_3[] PROGMEM = "Dimmer"; //V_DIMMER -char S_4[] PROGMEM = "Pressure"; //V_PRESSURE -char S_5[] PROGMEM = "Forecast"; //V_FORECAST -char S_6[] PROGMEM = "Rain"; //V_RAIN -char S_7[] PROGMEM = "Rainrate"; //V_RAINRATE -char S_8[] PROGMEM = "Wind"; //V_WIND -char S_9[] PROGMEM = "Gust"; //V_GUST -char S_10[] PROGMEM = "Direction"; //V_DIRECTION -char S_11[] PROGMEM = "UV"; //V_UV -char S_12[] PROGMEM = "Weight"; //V_WEIGHT -char S_13[] PROGMEM = "Distance"; //V_DISTANCE -char S_14[] PROGMEM = "Impedance"; //V_IMPEDANCE -char S_15[] PROGMEM = "Armed"; //V_ARMED -char S_16[] PROGMEM = "Tripped"; //V_TRIPPED -char S_17[] PROGMEM = "Watt"; //V_WATT -char S_18[] PROGMEM = "KWH"; //V_KWH -char S_19[] PROGMEM = "Scene_ON"; //V_SCENE_ON -char S_20[] PROGMEM = "Scene_OFF"; //V_SCENE_OFF -char S_21[] PROGMEM = "Heater"; //V_HEATER -char S_22[] PROGMEM = "Heater_SW"; //V_HEATER_SW -char S_23[] PROGMEM = "LightLevel"; //V_LIGHT_LEVEL -char S_24[] PROGMEM = "Var1"; //V_VAR1 -char S_25[] PROGMEM = "Var2"; //V_VAR2 -char S_26[] PROGMEM = "Var3"; //V_VAR3 -char S_27[] PROGMEM = "Var4"; //V_VAR4 -char S_28[] PROGMEM = "Var5,"; //V_VAR5 -char S_29[] PROGMEM = "Up"; //V_UP -char S_30[] PROGMEM = "Down"; //V_DOWN -char S_31[] PROGMEM = "Stop"; //V_STOP -char S_32[] PROGMEM = "IR_Send"; //V_IR_SEND -char S_33[] PROGMEM = "IR_Receive"; //V_IR_RECEIVE -char S_34[] PROGMEM = "Flow"; //V_FLOW -char S_35[] PROGMEM = "Volume"; //V_VOLUME -char S_36[] PROGMEM = "Lock_Status";//V_LOCK_STATUS -char S_37[] PROGMEM = "DustLevel"; //V_DUST_LEVEL -char S_38[] PROGMEM = ""; -char S_39[] PROGMEM = ""; -char S_40[] PROGMEM = ""; -char S_41[] PROGMEM = ""; -char S_42[] PROGMEM = ""; -char S_43[] PROGMEM = ""; -char S_44[] PROGMEM = ""; -char S_45[] PROGMEM = "Volt_Batt"; // Does not exist in MyMessage.h! -char S_46[] PROGMEM = ""; -char S_47[] PROGMEM = ""; -char S_48[] PROGMEM = ""; -char S_49[] PROGMEM = "Sketch_name"; // Does not exist in MyMessage.h! -char S_50[] PROGMEM = "Sketch_version"; // Does not exist in MyMessage.h! - - -PROGMEM const char *sType[] = { - S_0, S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, - S_11, S_12, S_13, S_14, S_15, S_16, S_17, S_18, S_19, S_20, - S_21, S_22, S_23, S_24, S_25, S_26, S_27, S_28, S_29, S_30, - S_31, S_32, S_33, S_34, S_35, S_36, S_37, S_38, S_39, S_40, - S_41, S_42, S_43, S_44, S_45, S_46, S_47, S_48, S_49, S_50 -}; - +#define S_FIRSTCUSTOM 60 +#define TYPEMAXLEN 20 +#define V_TOTAL (sizeof(vType)/sizeof(char *))-1 extern volatile uint8_t countRx; extern volatile uint8_t countTx; @@ -90,11 +108,32 @@ MySensor(_cepin, _cspin) { } -void MyMQTT::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate, void (*inDataCallback)(const char *, int *), uint8_t _rx, uint8_t _tx, uint8_t _er) { +inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, uint8_t sensor, uint8_t command, uint8_t type, bool enableAck) { + msg.destination = destination; + msg.sender = sender; + msg.sensor = sensor; + msg.type = type; + mSetCommand(msg,command); + mSetRequestAck(msg,enableAck); + mSetAck(msg,false); + return msg; +} + +char *getType(char *b, const char **index) { + char *q = b; + char *p = (char *)pgm_read_ptr(index); + while (*q++ = pgm_read_byte(p++)); + *q=0; + return b; +} + +void MyMQTT::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate, void (*inDataCallback) + (const char *, uint8_t *), uint8_t _rx, uint8_t _tx, uint8_t _er) { Serial.begin(BAUD_RATE); repeaterMode = true; isGateway = true; MQTTClientConnected = false; + setupRepeaterMode(); dataCallback = inDataCallback; @@ -117,10 +156,7 @@ void MyMQTT::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataR MsTimer2::set(200, ledTimersInterrupt); MsTimer2::start(); - - // Send startup log message on serial - //Serial.print(PSTR("Started\n"));//TODO: progmem gives error..? error: sType causes a section type conflict with __c - Serial.print("Started\n");//TODO: fix this... + Serial.print(getType(convBuf, &vType[S_FIRSTCUSTOM])); } void MyMQTT::processRadioMessage() { @@ -134,104 +170,97 @@ void MyMQTT::processRadioMessage() { } -void MyMQTT::processMQTTMessage(char *inputString, int inputPos) { +void MyMQTT::processMQTTMessage(char *inputString, uint8_t inputPos) { char *str, *p; - char i = 0; + uint8_t i = 0; buffer[0]= 0; buffsize = 0; -#ifdef TCPDUMP - Serial.print("<<"); - char buf[4]; - for (int a=0; a> 4 == MQTTCONNECT) { + + if ((uint8_t)inputString[0] >> 4 == MQTTCONNECT) { buffer[buffsize++] = MQTTCONNACK << 4; - buffer[buffsize++] = 0x02; // Remaining length - buffer[buffsize++] = 0x00; // Connection accepted - buffer[buffsize++] = 0x00; // Reserved - MQTTClientConnected=true; + buffer[buffsize++] = 0x02; // Remaining length + buffer[buffsize++] = 0x00; // Connection accepted + buffer[buffsize++] = 0x00; // Reserved + MQTTClientConnected=true; // We have connection! } - if ((byte)inputString[0] >> 4 == MQTTPINGREQ) { + if ((uint8_t)inputString[0] >> 4 == MQTTPINGREQ) { buffer[buffsize++] = MQTTPINGRESP << 4; buffer[buffsize++] = 0x00; } - if ((byte)inputString[0] >> 4 == MQTTSUBSCRIBE) { - buffer[buffsize++] = MQTTSUBACK << 4; // Just ack everything, we actually dont really care! - buffer[buffsize++] = 0x03; // Remaining length - buffer[buffsize++] = (byte)inputString[2]; // Message ID MSB - buffer[buffsize++] = (byte)inputString[3]; // Message ID LSB - buffer[buffsize++] = MQTTQOS0; // QOS level + if ((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE) { + buffer[buffsize++] = MQTTSUBACK << 4; // Just ack everything, we actually dont really care! + buffer[buffsize++] = 0x03; // Remaining length + buffer[buffsize++] = (uint8_t)inputString[2]; // Message ID MSB + buffer[buffsize++] = (uint8_t)inputString[3]; // Message ID LSB + buffer[buffsize++] = MQTTQOS0; // QOS level } - if ((byte)inputString[0] >> 4 == MQTTUNSUBSCRIBE) { + if ((uint8_t)inputString[0] >> 4 == MQTTUNSUBSCRIBE) { buffer[buffsize++] = MQTTUNSUBACK << 4; - buffer[buffsize++] = 0x02; // Remaining length - buffer[buffsize++] = (byte)inputString[2]; // Message ID MSB - buffer[buffsize++] = (byte)inputString[3]; // Message ID LSB + buffer[buffsize++] = 0x02; // Remaining length + buffer[buffsize++] = (uint8_t)inputString[2]; // Message ID MSB + buffer[buffsize++] = (uint8_t)inputString[3]; // Message ID LSB } - if ((byte)inputString[0] >> 4 == MQTTDISCONNECT) { - MQTTClientConnected=false; + if ((uint8_t)inputString[0] >> 4 == MQTTDISCONNECT) { + MQTTClientConnected=false; // We lost connection! } if (buffsize > 0) { -#ifdef TCPDUMP - Serial.print(">>"); - char buf[4]; - for (int a=0; a> 4 == MQTTPUBLISH || (MQTT_SEND_SUBSCRIPTION && (byte)inputString[0] >> 4 == MQTTSUBSCRIBE)) { + if ((uint8_t)inputString[0] >> 4 == MQTTPUBLISH || (MQTT_SEND_SUBSCRIPTION && (uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE)) { buffer[0]= 0; buffsize = 0; - if ((byte)inputString[0] >> 4 == MQTTSUBSCRIBE) { + // Cut out address and payload depending on message type. + if ((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE) { strncat(buffer,inputString+6,inputString[5]); } else { strncat(buffer,inputString+4,inputString[3]); } - msg.sender = GATEWAY_ADDRESS; - for (str = strtok_r(buffer,"/",&p) ; str && i<4 ; str = strtok_r(NULL,"/",&p)) { //split using semicolon - // TODO: Check if we should send ack or not. + + // TODO: Check if we should send ack or not. + for (str = strtok_r(buffer,"/",&p) ; str && i<4 ; str = strtok_r(NULL,"/",&p)) { if (i == 0) { - if (strcmp_P(str,broker)!=0) { - return; //Message not for us or malformatted! + if (strcmp_P(str,broker)!=0) { //look for MQTT_BROKER_PREFIX + return; //Message not for us or malformatted! } } else if (i==1) { - msg.destination = atoi(str); + msg.destination = atoi(str); //NodeID } else if (i==2) { - msg.sensor = atoi(str); + msg.sensor = atoi(str); //SensorID } else if (i==3) { - char match=0; - for (int j=0; strcpy_P(convBuf, (char*)pgm_read_word(&(sType[j]))) ; j++) { - if (strcmp(str,convBuf)==0) { + char match=0; //SensorType + //strcpy(str,(char*)&str[2]); //Strip V_ + + for (uint8_t j=0; strcpy_P(convBuf, (char*)pgm_read_word(&(vType[j]))) ; j++) { + if (strcmp((char*)&str[2],convBuf)==0) { //Strip V_ and compare match=j; break; } + if (j >= V_TOTAL) { // No match found! + match=V_TOTAL; // last item. + break; + } } msg.type = match; } i++; - } - if ((char)inputString[1] > (char)(inputString[3]+2) && !((byte)inputString[0] >> 4 == MQTTSUBSCRIBE)) { + } //Check if packge has payload + if ((uint8_t)inputString[1] > (uint8_t)(inputString[3]+2) && !((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE)) { strcpy(convBuf,inputString+(inputString[3]+4)); - msg.set(convBuf); + msg.set(convBuf); //Payload } else { - msg.set(""); + msg.set(""); //No payload } - msg.sender = GATEWAY_ADDRESS; - mSetCommand(msg,C_SET); - mSetRequestAck(msg,false); - mSetAck(msg,false); - mSetVersion(msg, PROTOCOL_VERSION); txBlink(1); - if (!sendRoute(msg)) errBlink(1); + if (!sendRoute(build(msg, GATEWAY_ADDRESS, msg.destination, msg.sensor, C_SET, msg.type, 0))) errBlink(1); + } } - void MyMQTT::SendMQTT(MyMessage &msg) { - //serial(PSTR("%d;%d;%d;%d;%s\n"),msg.sender, msg.sensor, mGetCommand(msg), msg.type, msg.getString(convBuf)); buffsize = 0; - if (!MQTTClientConnected) return; + if (!MQTTClientConnected) return; //We have no connections - return if (msg.isAck()) { Serial.println("msg is ack!"); if (msg.sender==255 && mGetCommand(msg)==C_INTERNAL && msg.type==I_ID_REQUEST) { @@ -246,95 +275,52 @@ void MyMQTT::SendMQTT(MyMessage &msg) { if (msg.sender==newNodeID) { saveState(EEPROM_LATEST_NODE_ADDRESS,newNodeID); } - if (mGetCommand(msg)==C_INTERNAL && msg.type==I_CONFIG) { // CONFIG - // As for now there is only one 'config' request. - // We force SI! Resistance is futile! - // - // Todo : Support for more config types, Maybe just read from own EEPROM? - // Use internal EEPROM_CONTROLLER_CONFIG_ADDRESS and special MQTT address to write to - // EEPROM_CONTROLLER_CONFIG_ADDRESS & EEPROM_LOCAL_CONFIG_ADDRESS - msg.destination = msg.sender; //NodeID - msg.sender = GATEWAY_ADDRESS; - msg.sensor = 255; //SensorID - msg.type = I_CONFIG; //msgType - mSetCommand(msg,C_INTERNAL);//Subtype - mSetRequestAck(msg,false); - mSetAck(msg,false); - msg.set("M"); - mSetVersion(msg, PROTOCOL_VERSION); - txBlink(1); - if (!sendRoute(msg)) errBlink(1); - } else if (mGetCommand(msg)==C_PRESENTATION && (msg.type==S_ARDUINO_NODE || msg.type==S_ARDUINO_REPEATER_NODE)) { - //Doesnt work to check new sensorID here, this message does not always arrive.. See above. - } else if (msg.sender==255 && mGetCommand(msg)==C_INTERNAL && msg.type==I_ID_REQUEST) { - unsigned char newNodeID = loadState(EEPROM_LATEST_NODE_ADDRESS)+1; - if (newNodeID <= MQTT_FIRST_SENSORID) newNodeID = MQTT_FIRST_SENSORID; - if (newNodeID >= MQTT_LAST_SENSORID) return; // Sorry no more id's left :( - msg.destination = msg.sender; //NodeID - msg.sender = GATEWAY_ADDRESS; - msg.sensor = 255; //SensorID - msg.type = I_ID_RESPONSE; //MsgType - mSetCommand(msg,C_INTERNAL); //Subtype - mSetRequestAck(msg,false); //Request ack doesn't work, node/gateway gets stuck in enless loop. - mSetAck(msg,false); - msg.set((uint8_t)newNodeID); //Payload - mSetVersion(msg, PROTOCOL_VERSION); - txBlink(1); - if (!sendRoute(msg)) errBlink(1); - // if (sendRoute(msg)) saveState(EEPROM_LATEST_NODE_ADDRESS,newNodeID); // If send OK save to eeprom. DOES NOT ALWAYS RETURN 'OK'!? + if (mGetCommand(msg)==C_INTERNAL) { + if (msg.type==I_CONFIG) { + txBlink(1); + if (!sendRoute(build(msg, GATEWAY_ADDRESS, msg.sender, 255, C_INTERNAL, I_CONFIG, 0).set("M"))) errBlink(1); + } else if (msg.type==I_ID_REQUEST && msg.sender==255) { + uint8_t newNodeID = loadState(EEPROM_LATEST_NODE_ADDRESS)+1; + if (newNodeID <= MQTT_FIRST_SENSORID) newNodeID = MQTT_FIRST_SENSORID; + if (newNodeID >= MQTT_LAST_SENSORID) return; // Sorry no more id's left :( + txBlink(1); + if (!sendRoute(build(msg, GATEWAY_ADDRESS, msg.sender, 255, C_INTERNAL, I_ID_RESPONSE, 0).set(newNodeID))) errBlink(1); + } } else if (mGetCommand(msg)!=0) { - if (mGetCommand(msg)==3) msg.type=msg.type+38; - buffer[buffsize++] = MQTTPUBLISH << 4; // 0: - buffer[buffsize++] = 0x09; // 1: Remaining length with no payload, we'll set this later to correct value, buffsize -2 - buffer[buffsize++] = 0x00; // 2: Length MSB (Remaing length can never exceed ff,so MSB must be 0!) - buffer[buffsize++] = 0x08; // 3: Length LSB (ADDR), We'll set this later + if (mGetCommand(msg)==3) msg.type=msg.type+(S_FIRSTCUSTOM-10); //Special message + + buffer[buffsize++] = MQTTPUBLISH << 4; // 0: + buffer[buffsize++] = 0x09; // 1: Remaining length with no payload, we'll set this later to correct value, buffsize -2 + buffer[buffsize++] = 0x00; // 2: Length MSB (Remaing length can never exceed ff,so MSB must be 0!) + buffer[buffsize++] = 0x08; // 3: Length LSB (ADDR), We'll set this later + if (msg.type > V_TOTAL) msg.type=V_TOTAL;// If type > defined types set to unknown. strcpy_P(buffer+4, broker); buffsize+=strlen_P(broker); - buffsize+=sprintf(&buffer[buffsize],"/%i/%i/",msg.sender,msg.sensor); - buffsize+=strncpysType_retL(buffer,msg.type,buffsize); - buffer[3]=buffsize-4; // Set correct address length on byte 4. + buffsize+=sprintf(&buffer[buffsize],"/%i/%i/V_%s",msg.sender,msg.sensor,getType(convBuf, &vType[msg.type])); + buffer[3]=buffsize-4; // Set correct address length on byte 4. #ifdef DEBUG Serial.println((char*)&buffer[4]); #endif msg.getString(convBuf); - for (unsigned int a=0; a>"); - char buf[4]; - for (int a=0; a0) otherwise the code might do strange things. -/////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////// #define EEPROM_LATEST_NODE_ADDRESS ((uint8_t)EEPROM_LOCAL_CONFIG_ADDRESS) #define MQTT_MAX_PACKET_SIZE 100 @@ -56,29 +55,27 @@ version 2 as published by the Free Software Foundation. class MyMQTT : public MySensor { + public: MyMQTT(uint8_t _cepin=5, uint8_t _cspin=6); - void begin(rf24_pa_dbm_e paLevel=RF24_PA_LEVEL_GW, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE, void (*dataCallback)(const char *, int *)=NULL, uint8_t _rx=6, uint8_t _tx=5, uint8_t _er=4 ); + void begin(rf24_pa_dbm_e paLevel=RF24_PA_LEVEL_GW, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE, void (*dataCallback) + (const char *, uint8_t *)=NULL, uint8_t _rx=6, uint8_t _tx=5, uint8_t _er=4 ); void processRadioMessage(); - void processMQTTMessage(char *inputString, int inputPos); + void processMQTTMessage(char *inputString, uint8_t inputPos); private: - bool MQTTClientConnected; - char buffer[MQTT_MAX_PACKET_SIZE]; - int buffsize; - char convBuf[MAX_PAYLOAD*2+1]; - boolean useWriteCallback; - void (*dataCallback)(const char *, int *); + void (*dataCallback)(const char *, uint8_t *); void SendMQTT(MyMessage &msg); - char strncpysType_retL(char *str, unsigned char index, char start); - - void ledTimers(); void rxBlink(uint8_t cnt); void txBlink(uint8_t cnt); void errBlink(uint8_t cnt); + + bool MQTTClientConnected; + char buffer[MQTT_MAX_PACKET_SIZE]; + char convBuf[MAX_PAYLOAD*2+1]; + uint8_t buffsize; }; extern void ledTimersInterrupt(); - #endif diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino old mode 100644 new mode 100755 index 3cb651a..29f6551 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -31,18 +31,19 @@ This will listen on your selected TCP_IP:TCP_PORT below, Please change TCP_MAC y message has any length or not. Example: if (msg.type==V_LIGHT && strlen(msg.getString())>0) otherwise the code might do strange things. -* Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/[SensorType] +* Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/V_[SensorType] NodeID and SensorID is uint8 (0-255) number. Last segment is translation of the sensor type, look inside MyMQTT.cpp for the definitions. User can change this to their needs. We have also left some space for custom types. Special: (sensor 255 reserved for special commands) -You can receive a node sketch name with MyMQTT/20/255/Sketch_name (or version with _version) +You can receive a node sketch name with MyMQTT/20/255/V_Sketch_name (or version with _version) To-do: Special commands : clear or set EEPROM Values, Send REBOOT and Receive reboot for MyMQTT itself. Be able to send ACK so client returns the data being sent. ... Please come with ideas! +What to do with publish messages. Test in more MQTT clients, So far tested in openhab and MyMQTT for Android (Not my creation) - http://www.openhab.org/ @@ -50,51 +51,16 @@ Test in more MQTT clients, So far tested in openhab and MyMQTT for Android (Not ... Please notify me if you use this broker with other software. -* Example Openhab configuration: -openhab.cfg ---- -mqtt:mysensor.url=tcp://192.168.0.234:1883 -mqtt:mysensor.clientId=MQTT ---- - -items/test.items ---- -Group test -Number Temp_test "Temp [%.1f °C]" (test) {mqtt="<[mysensor:MyMQTT/20/#/Temperature:state:default]"} -Number Hum_test "Hum [%.1f %%]" (test) {mqtt="<[mysensor:MyMQTT/20/#/Humidity:state:default]"} -Number test_test "test [%s]" (test) {mqtt="<[mysensor:MyMQTT/20/3/#:state:default]"} -Switch sw1 "sw 1" (test) {mqtt="<[mysensor:MyMQTT/21/1/Light:command:MAP(1on0off.map)]"} -Switch sw2 "sw2 recieve example" (test) {mqtt=">[mysensor:MyMQTT/21/2/Light:command:ON:1], - >[mysensor:MyMQTT/21/2/Light:command:OFF:0]"} -Switch sw3 "sw2 send + recieve example" (test) {mqtt=">[mysensor:MyMQTT/21/2/Light:command:ON:1], - >[mysensor:MyMQTT/21/2/Light:command:OFF:0],<[mysensor:MyMQTT/21/2/Light:command:MAP(1on0off.map)]"} -String sketch20 "Node 20 Sketch name [%s]" (test) {mqtt="<[mysensor:MyMQTT/20/255/Sketch_name:state:default]"} -String sketch21 "Node 21 Sketch name [%s]" (test) {mqtt="<[mysensor:MyMQTT/21/255/Sketch_name:state:default]"} ---- (Note; # = Wildcard character) - -sitemap/test.site ---- -sitemap demo label="Menu" -Frame label="Openhab" { - Group item=test label="Test group" -} ---- - -transform/1on0off.map ---- -1=ON -0=OFF ---- +* How to set-up Openhab and MQTTGateway: +http://forum.mysensors.org/topic/303/mqtt-broker-gateway */ - #include #include #include - -// Use this for IBOARD modded to use standard MISO/MOSI/SCK, see note *1 above! +// * Use this for IBOARD modded to use standard MISO/MOSI/SCK, see note *1 above! /* #define RADIO_CE_PIN 3 // radio chip enable #define RADIO_SPI_SS_PIN 8 // radio SPI serial select @@ -102,7 +68,7 @@ transform/1on0off.map #define RADIO_RX_LED_PIN A1 // Receive led pin #define RADIO_TX_LED_PIN A0 // the PCB, on board LED*/ -//Use this for default configured pro mini / nano etc : +// * Use this for default configured pro mini / nano etc : ///* #define RADIO_CE_PIN 5 // radio chip enable #define RADIO_SPI_SS_PIN 6 // radio SPI serial select @@ -110,19 +76,18 @@ transform/1on0off.map #define RADIO_RX_LED_PIN 8 // Receive led pin #define RADIO_TX_LED_PIN 9 // the PCB, on board LED*/ -#define TCP_PORT 1883 // Set your MQTT Broker Listening port. -IPAddress TCP_IP ( 192, 168, 0, 234 ); // Configure your static ip-address here -byte TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You should change this! see note *2 above! +#define TCP_PORT 1883 // Set your MQTT Broker Listening port. +IPAddress TCP_IP ( 192, 168, 0, 234 ); // Configure your static ip-address here +uint8_t TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You should change this! see note *2 above! + +////////////////////////////////////////////////////////////////// EthernetServer server = EthernetServer(TCP_PORT); MyMQTT gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN); -// -- Uncomment this constructor if you have leds and include button attached to your gateway -//MyMQTT gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN); - void processEthernetMessages() { char inputString[MQTT_MAX_PACKET_SIZE] = ""; - int inputSize = 0; + uint8_t inputSize = 0; EthernetClient client = server.available(); if (client) { while (client.available()) { @@ -130,23 +95,33 @@ void processEthernetMessages() { inputString[inputSize] = inChar; inputSize++; } +#ifdef TCPDUMP + Serial.print("<<"); + char buf[4]; + for (uint8_t a=0; a>"); + char buf[4]; + for (uint8_t a=0; a<*writeSize; a++) { sprintf(buf,"%02X ",(uint8_t)writeBuffer[a]); Serial.print(buf); } Serial.println(""); +#endif + server.write((const uint8_t *)writeBuffer, *writeSize); } + int main(void) { init(); Ethernet.begin(TCP_MAC, TCP_IP); delay(1000); // Wait for Ethernet to get configured. - gw.begin(RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE, writeEthernet); + gw.begin(RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE, writeEthernet, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN); server.begin(); while (1) { processEthernetMessages(); gw.processRadioMessage(); } } - From 6dde2e428a35e8930214d816df3144fdf09e5985 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 27 Aug 2014 21:24:00 +0200 Subject: [PATCH 005/137] Need to include MySensor.h for gateway examples to work in codebender. --- README.md | 2 +- libraries/MySensors/Version.h | 2 +- .../MySensors/examples/EthernetGateway/EthernetGateway.ino | 5 +++-- libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino | 1 + libraries/MySensors/examples/SerialGateway/SerialGateway.ino | 1 + 5 files changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 4df7c40..ebb4f31 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Arduino ======= -MySensors Arduino Library +MySensors Arduino Library v1.4 Please visit www.mysensors.org for more information diff --git a/libraries/MySensors/Version.h b/libraries/MySensors/Version.h index bc5edc4..026d736 100644 --- a/libraries/MySensors/Version.h +++ b/libraries/MySensors/Version.h @@ -6,6 +6,6 @@ #ifndef Version_h #define Version_h -#define LIBRARY_VERSION "1.4b1 (18848a2)" +#define LIBRARY_VERSION "1.4" #endif diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 5932de6..df3b935 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -45,14 +45,15 @@ */ #include +#include #include #include // Use this if you have attached a Ethernet ENC28J60 shields -#include +//#include // Use this fo WizNET module and Arduino Ethernet Shield -//#include +#include #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index 29f6551..5050b59 100755 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -57,6 +57,7 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway */ #include +#include #include #include diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index a59de08..8c3a7dd 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -22,6 +22,7 @@ */ #include +#include #include #include From cc00bedaa1bb926da1f2a803cabd17e8a47130e7 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 27 Aug 2014 21:53:57 +0200 Subject: [PATCH 006/137] Classify method. --- libraries/MySensors/MyMQTT.cpp | 2 +- libraries/MySensors/MyMQTT.h | 2 ++ libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) mode change 100755 => 100644 libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino diff --git a/libraries/MySensors/MyMQTT.cpp b/libraries/MySensors/MyMQTT.cpp index 2ab42b5..f080790 100755 --- a/libraries/MySensors/MyMQTT.cpp +++ b/libraries/MySensors/MyMQTT.cpp @@ -119,7 +119,7 @@ inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, ui return msg; } -char *getType(char *b, const char **index) { +char *MyMQTT::getType(char *b, const char **index) { char *q = b; char *p = (char *)pgm_read_ptr(index); while (*q++ = pgm_read_byte(p++)); diff --git a/libraries/MySensors/MyMQTT.h b/libraries/MySensors/MyMQTT.h index 76d0830..e5d5447 100755 --- a/libraries/MySensors/MyMQTT.h +++ b/libraries/MySensors/MyMQTT.h @@ -14,6 +14,7 @@ version 2 as published by the Free Software Foundation. #include "MySensor.h" + ////////////////////////////////////////////////////////////////// #ifdef DEBUG @@ -74,6 +75,7 @@ private: char buffer[MQTT_MAX_PACKET_SIZE]; char convBuf[MAX_PAYLOAD*2+1]; uint8_t buffsize; + char *getType(char *b, const char **index); }; extern void ledTimersInterrupt(); diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino old mode 100755 new mode 100644 index 5050b59..bbd44dd --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -61,6 +61,7 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway #include #include + // * Use this for IBOARD modded to use standard MISO/MOSI/SCK, see note *1 above! /* #define RADIO_CE_PIN 3 // radio chip enable From ba098a95e20c55dc00f847f36c3746efa840bb87 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 27 Aug 2014 22:55:52 +0200 Subject: [PATCH 007/137] Fix compiler error. --- libraries/MySensors/MyMQTT.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MyMQTT.cpp b/libraries/MySensors/MyMQTT.cpp index f080790..610414e 100755 --- a/libraries/MySensors/MyMQTT.cpp +++ b/libraries/MySensors/MyMQTT.cpp @@ -121,7 +121,7 @@ inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, ui char *MyMQTT::getType(char *b, const char **index) { char *q = b; - char *p = (char *)pgm_read_ptr(index); + char *p = (char *)pgm_read_word(index); while (*q++ = pgm_read_byte(p++)); *q=0; return b; From 159c22388245bb0f6686efacc3c7ad2204b85e0d Mon Sep 17 00:00:00 2001 From: Daniel Wiegert Date: Thu, 28 Aug 2014 14:30:42 +0200 Subject: [PATCH 008/137] Include more debug text in MINIMAL definition, and enable MINIMAL as default, saves 432bytes --- libraries/MySensors/utility/RF24.cpp | 3 ++- libraries/MySensors/utility/RF24.h | 4 ++-- libraries/MySensors/utility/RF24_config.h | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) mode change 100644 => 100755 libraries/MySensors/utility/RF24.cpp mode change 100644 => 100755 libraries/MySensors/utility/RF24.h mode change 100644 => 100755 libraries/MySensors/utility/RF24_config.h diff --git a/libraries/MySensors/utility/RF24.cpp b/libraries/MySensors/utility/RF24.cpp old mode 100644 new mode 100755 index 2efb7bb..38053ab --- a/libraries/MySensors/utility/RF24.cpp +++ b/libraries/MySensors/utility/RF24.cpp @@ -270,6 +270,7 @@ uint8_t RF24::get_status(void) } /****************************************************************************/ +#if !defined (MINIMAL) void RF24::print_status(uint8_t status) { @@ -325,7 +326,7 @@ void RF24::print_address_register(const char* name, uint8_t reg, uint8_t qty) printf_P(PSTR("\r\n")); } - +#endif /****************************************************************************/ RF24::RF24(uint8_t _cepin, uint8_t _cspin): diff --git a/libraries/MySensors/utility/RF24.h b/libraries/MySensors/utility/RF24.h old mode 100644 new mode 100755 index 55253bb..89ed231 --- a/libraries/MySensors/utility/RF24.h +++ b/libraries/MySensors/utility/RF24.h @@ -863,7 +863,7 @@ private: * @return Current value of status register */ uint8_t get_status(void); - +#if !defined (MINIMAL) /** * Decode and print the given status to stdout * @@ -907,7 +907,7 @@ private: * @param qty How many successive registers to print */ void print_address_register(const char* name, uint8_t reg, uint8_t qty = 1); - +#endif /** * Turn on or off the special features of the chip * diff --git a/libraries/MySensors/utility/RF24_config.h b/libraries/MySensors/utility/RF24_config.h old mode 100644 new mode 100755 index b7154a5..55962f1 --- a/libraries/MySensors/utility/RF24_config.h +++ b/libraries/MySensors/utility/RF24_config.h @@ -21,7 +21,7 @@ #include //TMRh20: - //#define MINIMAL + #define MINIMAL // saves 432 bytes! // Define _BV for non-Arduino platforms and for Arduino DUE #if defined (ARDUINO) From 7fa54a6e5a2c6d1d58a2705d32d6fe88c151eeec Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 9 Sep 2014 16:57:56 +0200 Subject: [PATCH 009/137] Proposal to keep gateways separated. --- .../utility => MsTimer2}/MsTimer2.cpp | 0 .../utility => MsTimer2}/MsTimer2.h | 0 .../MsTimer2/examples/FlashLed/FlashLed.pde | 42 ++ libraries/MsTimer2/keywords.txt | 4 + libraries/MySensors/MyGateway.cpp | 297 -------- libraries/MySensors/MyGateway.h | 72 -- libraries/MySensors/MyMQTT.cpp | 326 --------- libraries/MySensors/MySensor.cpp | 9 +- libraries/MySensors/MySensor.h | 2 +- .../EthernetGateway/EthernetGateway.ino | 58 +- .../examples/EthernetGateway/GatewayUtil.h | 262 +++++++ .../examples/MQTTGateway/GatewayUtil.h | 120 ++++ .../examples/MQTTGateway/MQTTGateway.ino | 319 ++++++++- .../MySensors/examples/MQTTGateway/MyMQTT.h | 138 ++++ .../MQTTGateway/MyMQTT.hx} | 0 .../examples/SerialGateway/GatewayUtil.h | 262 +++++++ .../examples/SerialGateway/SerialGateway.ino | 59 +- .../Examples/ByteBuffer/ByteBuffer.cpp | 272 +++++++ .../Examples/ByteBuffer/ByteBuffer.h | 104 +++ .../PinChangeInt/Examples/GetPSTR/GetPSTR.h | 21 + .../PinChangeIntExample.pde | 77 ++ .../PinChangeIntSpeedTest.pde | 265 +++++++ .../PinChangeIntTest/PinChangeIntTest.pde | 344 +++++++++ .../PinChangeIntTest2/PinChangeIntTest2.ino | 275 +++++++ .../utility => PinChangeInt}/PinChangeInt.h | 0 libraries/PinChangeInt/RELEASE_NOTES | 332 +++++++++ libraries/PinChangeInt/gpl.txt | 674 ++++++++++++++++++ libraries/PinChangeInt/keywords.txt | 10 + 28 files changed, 3604 insertions(+), 740 deletions(-) rename libraries/{MySensors/utility => MsTimer2}/MsTimer2.cpp (100%) rename libraries/{MySensors/utility => MsTimer2}/MsTimer2.h (100%) create mode 100644 libraries/MsTimer2/examples/FlashLed/FlashLed.pde create mode 100644 libraries/MsTimer2/keywords.txt delete mode 100644 libraries/MySensors/MyGateway.cpp delete mode 100644 libraries/MySensors/MyGateway.h delete mode 100755 libraries/MySensors/MyMQTT.cpp create mode 100644 libraries/MySensors/examples/EthernetGateway/GatewayUtil.h create mode 100644 libraries/MySensors/examples/MQTTGateway/GatewayUtil.h create mode 100644 libraries/MySensors/examples/MQTTGateway/MyMQTT.h rename libraries/MySensors/{MyMQTT.h => examples/MQTTGateway/MyMQTT.hx} (100%) create mode 100644 libraries/MySensors/examples/SerialGateway/GatewayUtil.h create mode 100644 libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.cpp create mode 100644 libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.h create mode 100644 libraries/PinChangeInt/Examples/GetPSTR/GetPSTR.h create mode 100644 libraries/PinChangeInt/Examples/PinChangeIntExample/PinChangeIntExample.pde create mode 100644 libraries/PinChangeInt/Examples/PinChangeIntSpeedTest/PinChangeIntSpeedTest.pde create mode 100644 libraries/PinChangeInt/Examples/PinChangeIntTest/PinChangeIntTest.pde create mode 100644 libraries/PinChangeInt/Examples/PinChangeIntTest2/PinChangeIntTest2.ino rename libraries/{MySensors/utility => PinChangeInt}/PinChangeInt.h (100%) create mode 100644 libraries/PinChangeInt/RELEASE_NOTES create mode 100644 libraries/PinChangeInt/gpl.txt create mode 100644 libraries/PinChangeInt/keywords.txt diff --git a/libraries/MySensors/utility/MsTimer2.cpp b/libraries/MsTimer2/MsTimer2.cpp similarity index 100% rename from libraries/MySensors/utility/MsTimer2.cpp rename to libraries/MsTimer2/MsTimer2.cpp diff --git a/libraries/MySensors/utility/MsTimer2.h b/libraries/MsTimer2/MsTimer2.h similarity index 100% rename from libraries/MySensors/utility/MsTimer2.h rename to libraries/MsTimer2/MsTimer2.h diff --git a/libraries/MsTimer2/examples/FlashLed/FlashLed.pde b/libraries/MsTimer2/examples/FlashLed/FlashLed.pde new file mode 100644 index 0000000..4d04496 --- /dev/null +++ b/libraries/MsTimer2/examples/FlashLed/FlashLed.pde @@ -0,0 +1,42 @@ +char dummyvar; // to get Arduinoi IDE to include core headers properly + +/* + MsTimer2 is a small and very easy to use library to interface Timer2 with + humans. It's called MsTimer2 because it "hardcodes" a resolution of 1 + millisecond on timer2 + For Details see: http://www.arduino.cc/playground/Main/MsTimer2 +*/ +#include + +// Switch on LED on and off each half second + +#if defined(ARDUINO) && ARDUINO >= 100 +const int led_pin = LED_BUILTIN; // 1.0 built in LED pin var +#else +#if defined(CORE_LED0_PIN) +const int led_pin = CORE_LED0_PIN; // 3rd party LED pin define +#else +const int led_pin = 13; // default to pin 13 +#endif +#endif + + +void flash() +{ + static boolean output = HIGH; + + digitalWrite(led_pin, output); + output = !output; +} + +void setup() +{ + pinMode(led_pin, OUTPUT); + + MsTimer2::set(500, flash); // 500ms period + MsTimer2::start(); +} + +void loop() +{ +} diff --git a/libraries/MsTimer2/keywords.txt b/libraries/MsTimer2/keywords.txt new file mode 100644 index 0000000..8b4fff7 --- /dev/null +++ b/libraries/MsTimer2/keywords.txt @@ -0,0 +1,4 @@ +MsTimer2 KEYWORD1 +set KEYWORD2 +start KEYWORD2 +stop KEYWORD2 diff --git a/libraries/MySensors/MyGateway.cpp b/libraries/MySensors/MyGateway.cpp deleted file mode 100644 index 2785ec9..0000000 --- a/libraries/MySensors/MyGateway.cpp +++ /dev/null @@ -1,297 +0,0 @@ -/* - The MySensors library adds a new layer on top of the RF24 library. - It handles radio network routing, relaying and ids. - - Created by Henrik Ekblad - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - version 2 as published by the Free Software Foundation. -*/ - -#include "MyGateway.h" -#include "utility/MsTimer2.h" -#include "utility/PinChangeInt.h" - - -uint8_t pinRx; -uint8_t pinTx; -uint8_t pinEr; -boolean buttonTriggeredInclusion; -volatile uint8_t countRx; -volatile uint8_t countTx; -volatile uint8_t countErr; -boolean inclusionMode; // Keeps track on inclusion mode - - -MyGateway::MyGateway(uint8_t _cepin, uint8_t _cspin, uint8_t _inclusion_time, uint8_t _inclusion_pin, uint8_t _rx, uint8_t _tx, uint8_t _er) : MySensor(_cepin, _cspin) { - pinInclusion = _inclusion_pin; - inclusionTime = _inclusion_time; - pinRx = _rx; - pinTx = _tx; - pinEr = _er; -} - - -void MyGateway::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate, void (*inDataCallback)(char *)) { - Serial.begin(BAUD_RATE); - repeaterMode = true; - isGateway = true; - setupRepeaterMode(); - - if (inDataCallback != NULL) { - useWriteCallback = true; - dataCallback = inDataCallback; - } else { - useWriteCallback = false; - } - - nc.nodeId = 0; - nc.distance = 0; - inclusionMode = 0; - buttonTriggeredInclusion = false; - countRx = 0; - countTx = 0; - countErr = 0; - - // Setup led pins - pinMode(pinRx, OUTPUT); - pinMode(pinTx, OUTPUT); - pinMode(pinEr, OUTPUT); - digitalWrite(pinRx, LOW); - digitalWrite(pinTx, LOW); - digitalWrite(pinEr, LOW); - - // Setup digital in that triggers inclusion mode - pinMode(pinInclusion, INPUT); - digitalWrite(pinInclusion, HIGH); - - // Set initial state of leds - digitalWrite(pinRx, HIGH); - digitalWrite(pinTx, HIGH); - digitalWrite(pinEr, HIGH); - - - // Start up the radio library - setupRadio(paLevel, channel, dataRate); - RF24::openReadingPipe(WRITE_PIPE, BASE_RADIO_ID); - RF24::openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); - RF24::startListening(); - - // Add led timer interrupt - MsTimer2::set(300, ledTimersInterrupt); - MsTimer2::start(); - - // Add interrupt for inclusion button to pin - PCintPort::attachInterrupt(pinInclusion, startInclusionInterrupt, RISING); - - // Send startup log message on serial - serial(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"), C_INTERNAL, I_GATEWAY_READY); -} - - -void startInclusionInterrupt() { - buttonTriggeredInclusion = true; -} - - - -void MyGateway::checkButtonTriggeredInclusion() { - if (buttonTriggeredInclusion) { - // Ok, someone pressed the inclusion button on the gateway - // start inclusion mode for 1 munute. - serial(PSTR("0;0;%d;0;%d;Inclusion started by button.\n"), C_INTERNAL, I_LOG_MESSAGE); - buttonTriggeredInclusion = false; - setInclusionMode(true); - } -} - -void MyGateway::checkInclusionFinished() { - if (inclusionMode && millis()-inclusionStartTime>60000UL*inclusionTime) { - // inclusionTimeInMinutes minute(s) has passed.. stop inclusion mode - setInclusionMode(false); - } -} - -uint8_t MyGateway::h2i(char c) { - uint8_t i = 0; - if (c <= '9') - i += c - '0'; - else if (c >= 'a') - i += c - 'a' + 10; - else - i += c - 'A' + 10; - return i; -} - -void MyGateway::parseAndSend(char *commandBuffer) { - boolean ok = false; - char *str, *p, *value=NULL; - uint8_t bvalue[MAX_PAYLOAD]; - uint8_t blen = 0; - int i = 0; - uint16_t destination = 0; - uint8_t sensor = 0; - uint8_t command = 0; - uint8_t type = 0; - uint8_t ack = 0; - - // Extract command data coming on serial line - for (str = strtok_r(commandBuffer, ";", &p); // split using semicolon - str && i < 6; // loop while str is not null an max 5 times - str = strtok_r(NULL, ";", &p) // get subsequent tokens - ) { - switch (i) { - case 0: // Radioid (destination) - destination = atoi(str); - break; - case 1: // Childid - sensor = atoi(str); - break; - case 2: // Message type - command = atoi(str); - break; - case 3: // Should we request ack from destination? - ack = atoi(str); - break; - case 4: // Data type - type = atoi(str); - break; - case 5: // Variable value - if (command == C_STREAM) { - blen = 0; - uint8_t val; - while (*str) { - val = h2i(*str++) << 4; - val += h2i(*str++); - bvalue[blen] = val; - blen++; - } - } else { - value = str; - // Remove ending carriage return character (if it exists) - uint8_t lastCharacter = strlen(value)-1; - if (value[lastCharacter] == '\r') - value[lastCharacter] = 0; - } - break; - } - i++; - } - - if (destination==GATEWAY_ADDRESS && command==C_INTERNAL) { - // Handle messages directed to gateway - if (type == I_VERSION) { - // Request for version - serial(PSTR("0;0;%d;0;%d;%s\n"),C_INTERNAL, I_VERSION, LIBRARY_VERSION); - } else if (type == I_INCLUSION_MODE) { - // Request to change inclusion mode - setInclusionMode(atoi(value) == 1); - } - } else { - txBlink(1); - msg.sender = GATEWAY_ADDRESS; - msg.destination = destination; - msg.sensor = sensor; - msg.type = type; - mSetCommand(msg,command); - mSetRequestAck(msg,ack?1:0); - mSetAck(msg,false); - if (command == C_STREAM) - msg.set(bvalue, blen); - else - msg.set(value); - ok = sendRoute(msg); - if (!ok) { - errBlink(1); - } - } -} - - -void MyGateway::setInclusionMode(boolean newMode) { - if (newMode != inclusionMode) - inclusionMode = newMode; - // Send back mode change on serial line to ack command - serial(PSTR("0;0;%d;0;%d;%d\n"), C_INTERNAL, I_INCLUSION_MODE, inclusionMode?1:0); - - if (inclusionMode) { - inclusionStartTime = millis(); - } -} - -void MyGateway::processRadioMessage() { - if (process()) { - // A new message was received from one of the sensors - MyMessage message = getLastMessage(); - if (mGetCommand(message) == C_PRESENTATION && inclusionMode) { - rxBlink(3); - } else { - rxBlink(1); - } - // Pass along the message from sensors to serial line - serial(message); - } - - checkButtonTriggeredInclusion(); - checkInclusionFinished(); -} - -void MyGateway::serial(const char *fmt, ... ) { - va_list args; - va_start (args, fmt ); - vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args); - va_end (args); - Serial.print(serialBuffer); - if (useWriteCallback) { - // We have a registered write callback (probably Ethernet) - dataCallback(serialBuffer); - } -} - -void MyGateway::serial(MyMessage &msg) { - serial(PSTR("%d;%d;%d;%d;%d;%s\n"),msg.sender, msg.sensor, mGetCommand(msg), mGetAck(msg), msg.type, msg.getString(convBuf)); -} - - -void ledTimersInterrupt() { - if(countRx && countRx != 255) { - // switch led on - digitalWrite(pinRx, LOW); - } else if(!countRx) { - // switching off - digitalWrite(pinRx, HIGH); - } - if(countRx != 255) { countRx--; } - - if(countTx && countTx != 255) { - // switch led on - digitalWrite(pinTx, LOW); - } else if(!countTx) { - // switching off - digitalWrite(pinTx, HIGH); - } - if(countTx != 255) { countTx--; } - else if(inclusionMode) { countTx = 8; } - - if(countErr && countErr != 255) { - // switch led on - digitalWrite(pinEr, LOW); - } else if(!countErr) { - // switching off - digitalWrite(pinEr, HIGH); - } - if(countErr != 255) { countErr--; } - -} - -void MyGateway::rxBlink(uint8_t cnt) { - if(countRx == 255) { countRx = cnt; } -} -void MyGateway::txBlink(uint8_t cnt) { - if(countTx == 255 && !inclusionMode) { countTx = cnt; } -} -void MyGateway::errBlink(uint8_t cnt) { - if(countErr == 255) { countErr = cnt; } -} - diff --git a/libraries/MySensors/MyGateway.h b/libraries/MySensors/MyGateway.h deleted file mode 100644 index 21a93d6..0000000 --- a/libraries/MySensors/MyGateway.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - The MySensors library adds a new layer on top of the RF24 library. - It handles radio network routing, relaying and ids. - - Created by Henrik Ekblad - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - version 2 as published by the Free Software Foundation. -*/ - -#ifndef MyGateway_h -#define MyGateway_h - -#include "MySensor.h" - -#define MAX_RECEIVE_LENGTH 100 // Max buffersize needed for messages coming from controller -#define MAX_SEND_LENGTH 120 // Max buffersize needed for messages destined for controller - -class MyGateway : public MySensor -{ - public: - /** - * Constructor - * - * Creates a new instance of MyGateway class. - * If you don't use status leds and/or inclusion mode button on your arduino gateway - * you can disable this functionality by calling the 2 argument constructor. - * - * @param _cepin The pin attached to RF24 Chip Enable on the RF module (default 9) - * @param _cspin The pin attached to RF24 Chip Select (defualt 10) - * @param _inclusion_time Time of inclusion mode (in minutes, default 1) - * @param _inclusion_pin Digital pin that triggers inclusion mode - * @param _rx Digital pin for receive led - * @param _tx Digital pin for transfer led - * @param _er Digital pin for error led - * - */ - MyGateway(uint8_t _cepin=DEFAULT_CE_PIN, uint8_t _cspin=DEFAULT_CS_PIN, uint8_t _inclusion_time = 1, uint8_t _inclusion_pin = 3, uint8_t _rx=6, uint8_t _tx=5, uint8_t _er=4); - - /* Use this and pass a function that should be called when you want to process commands that arrive from radio network */ - void begin(rf24_pa_dbm_e paLevel=RF24_PA_LEVEL_GW, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE, void (*dataCallback)(char *)=NULL); - - void processRadioMessage(); - void parseAndSend(char *inputString); - - private: - char convBuf[MAX_PAYLOAD*2+1]; - char serialBuffer[MAX_SEND_LENGTH]; // Buffer for building string when sending data to vera - unsigned long inclusionStartTime; - boolean useWriteCallback; - void (*dataCallback)(char *); - uint8_t pinInclusion; - uint8_t inclusionTime; - - uint8_t h2i(char c); - - void serial(const char *fmt, ... ); - void serial(MyMessage &msg); - void checkButtonTriggeredInclusion(); - void setInclusionMode(boolean newMode); - void checkInclusionFinished(); - void ledTimers(); - void rxBlink(uint8_t cnt); - void txBlink(uint8_t cnt); - void errBlink(uint8_t cnt); -}; - -void ledTimersInterrupt(); -void startInclusionInterrupt(); - -#endif diff --git a/libraries/MySensors/MyMQTT.cpp b/libraries/MySensors/MyMQTT.cpp deleted file mode 100755 index 610414e..0000000 --- a/libraries/MySensors/MyMQTT.cpp +++ /dev/null @@ -1,326 +0,0 @@ -/* -The MySensors library adds a new layer on top of the RF24 library. -It handles radio network routing, relaying and ids. - -Created by Henrik Ekblad -Modified by Daniel Wiegert -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -version 2 as published by the Free Software Foundation. -*/ - -#include "MyMQTT.h" -#include "utility/MsTimer2.h" - -char V_0[] PROGMEM = "TEMP"; //V_TEMP -char V_1[] PROGMEM = "HUM"; //V_HUM -char V_2[] PROGMEM = "LIGHT"; //V_LIGHT -char V_3[] PROGMEM = "DIMMER"; //V_DIMMER -char V_4[] PROGMEM = "PRESSURE"; //V_PRESSURE -char V_5[] PROGMEM = "FORECAST"; //V_FORECAST -char V_6[] PROGMEM = "RAIN"; //V_RAIN -char V_7[] PROGMEM = "RAINRATE"; //V_RAINRATE -char V_8[] PROGMEM = "WIND"; //V_WIND -char V_9[] PROGMEM = "GUST"; //V_GUST -char V_10[] PROGMEM = "DIRECTON"; //V_DIRECTON -char V_11[] PROGMEM = "UV"; //V_UV -char V_12[] PROGMEM = "WEIGHT"; //V_WEIGHT -char V_13[] PROGMEM = "DISTANCE"; //V_DISTANCE -char V_14[] PROGMEM = "IMPEDANCE"; //V_IMPEDANCE -char V_15[] PROGMEM = "ARMED"; //V_ARMED -char V_16[] PROGMEM = "TRIPPED"; //V_TRIPPED -char V_17[] PROGMEM = "WATT"; //V_WATT -char V_18[] PROGMEM = "KWH"; //V_KWH -char V_19[] PROGMEM = "SCENE_ON"; //V_SCENE_ON -char V_20[] PROGMEM = "SCENE_OFF"; //V_SCENE_OFF -char V_21[] PROGMEM = "HEATER"; //V_HEATER -char V_22[] PROGMEM = "HEATER_SW"; //V_HEATER_SW -char V_23[] PROGMEM = "LIGHT_LEVEL"; //V_LIGHT_LEVEL -char V_24[] PROGMEM = "VAR1"; //V_VAR1 -char V_25[] PROGMEM = "VAR2"; //V_VAR2 -char V_26[] PROGMEM = "VAR3"; //V_VAR3 -char V_27[] PROGMEM = "VAR4"; //V_VAR4 -char V_28[] PROGMEM = "VAR5"; //V_VAR5 -char V_29[] PROGMEM = "UP"; //V_UP -char V_30[] PROGMEM = "DOWN"; //V_DOWN -char V_31[] PROGMEM = "STOP"; //V_STOP -char V_32[] PROGMEM = "IR_SEND"; //V_IR_SEND -char V_33[] PROGMEM = "IR_RECEIVE"; //V_IR_RECEIVE -char V_34[] PROGMEM = "FLOW"; //V_FLOW -char V_35[] PROGMEM = "VOLUME"; //V_VOLUME -char V_36[] PROGMEM = "LOCK_STATUS"; //V_LOCK_STATUS -char V_37[] PROGMEM = "DUST_LEVEL"; //V_DUST_LEVEL -char V_38[] PROGMEM = "VOLTAGE"; //V_VOLTAGE -char V_39[] PROGMEM = "CURRENT"; //V_CURRENT -char V_40[] PROGMEM = ""; // -char V_41[] PROGMEM = ""; // -char V_42[] PROGMEM = ""; // -char V_43[] PROGMEM = ""; // -char V_44[] PROGMEM = ""; // -char V_45[] PROGMEM = ""; // -char V_46[] PROGMEM = ""; // -char V_47[] PROGMEM = ""; // -char V_48[] PROGMEM = ""; // -char V_49[] PROGMEM = ""; // -char V_50[] PROGMEM = ""; // -char V_51[] PROGMEM = ""; // -char V_52[] PROGMEM = ""; // -char V_53[] PROGMEM = ""; // -char V_54[] PROGMEM = ""; // -char V_55[] PROGMEM = ""; // -char V_56[] PROGMEM = ""; // -char V_57[] PROGMEM = ""; // -char V_58[] PROGMEM = ""; // -char V_59[] PROGMEM = ""; // -char V_60[] PROGMEM = "Started!\n"; //Custom for MQTTGateway -char V_61[] PROGMEM = "SKETCH_NAME"; //Custom for MQTTGateway -char V_62[] PROGMEM = "SKETCH_VERSION"; //Custom for MQTTGateway -char V_63[] PROGMEM = "UNKNOWN"; //Custom for MQTTGateway - -////////////////////////////////////////////////////////////////// - -PROGMEM const char *vType[] = { - V_0, V_1, V_2, V_3, V_4, V_5, V_6, V_7, V_8, V_9, V_10, - V_11, V_12, V_13, V_14, V_15, V_16, V_17, V_18, V_19, V_20, - V_21, V_22, V_23, V_24, V_25, V_26, V_27, V_28, V_29, V_30, - V_31, V_32, V_33, V_34, V_35, V_36, V_37, V_38, V_39, V_40, - V_41, V_42, V_43, V_44, V_45, V_46, V_47, V_48, V_49, V_50, - V_51, V_52, V_53, V_54, V_55, V_56, V_57, V_58, V_59, V_60, - V_61, V_62, V_63 -}; - - -char broker[] PROGMEM = MQTT_BROKER_PREFIX; - -#define S_FIRSTCUSTOM 60 -#define TYPEMAXLEN 20 -#define V_TOTAL (sizeof(vType)/sizeof(char *))-1 - -extern volatile uint8_t countRx; -extern volatile uint8_t countTx; -extern volatile uint8_t countErr; -extern uint8_t pinRx; -extern uint8_t pinTx; -extern uint8_t pinEr; - -MyMQTT::MyMQTT(uint8_t _cepin, uint8_t _cspin) : -MySensor(_cepin, _cspin) { - -} - -inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, uint8_t sensor, uint8_t command, uint8_t type, bool enableAck) { - msg.destination = destination; - msg.sender = sender; - msg.sensor = sensor; - msg.type = type; - mSetCommand(msg,command); - mSetRequestAck(msg,enableAck); - mSetAck(msg,false); - return msg; -} - -char *MyMQTT::getType(char *b, const char **index) { - char *q = b; - char *p = (char *)pgm_read_word(index); - while (*q++ = pgm_read_byte(p++)); - *q=0; - return b; -} - -void MyMQTT::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate, void (*inDataCallback) - (const char *, uint8_t *), uint8_t _rx, uint8_t _tx, uint8_t _er) { - Serial.begin(BAUD_RATE); - repeaterMode = true; - isGateway = true; - MQTTClientConnected = false; - - setupRepeaterMode(); - dataCallback = inDataCallback; - - nc.nodeId = 0; - nc.distance = 0; - - // Start up the radio library - setupRadio(paLevel, channel, dataRate); - RF24::openReadingPipe(WRITE_PIPE, BASE_RADIO_ID); - RF24::openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); - RF24::startListening(); - - pinRx = _rx; - pinMode(pinRx, OUTPUT); - pinTx = _tx; - pinMode(pinTx, OUTPUT); - pinEr = _er; - pinMode(pinEr, OUTPUT); - - MsTimer2::set(200, ledTimersInterrupt); - MsTimer2::start(); - - Serial.print(getType(convBuf, &vType[S_FIRSTCUSTOM])); -} - -void MyMQTT::processRadioMessage() { - if (process()) { - // A new message was received from one of the sensors - MyMessage message = getLastMessage(); - // Pass along the message from sensors to serial line - rxBlink(1); - SendMQTT(message); - } - -} - -void MyMQTT::processMQTTMessage(char *inputString, uint8_t inputPos) { - char *str, *p; - uint8_t i = 0; - buffer[0]= 0; - buffsize = 0; - - if ((uint8_t)inputString[0] >> 4 == MQTTCONNECT) { - buffer[buffsize++] = MQTTCONNACK << 4; - buffer[buffsize++] = 0x02; // Remaining length - buffer[buffsize++] = 0x00; // Connection accepted - buffer[buffsize++] = 0x00; // Reserved - MQTTClientConnected=true; // We have connection! - } - if ((uint8_t)inputString[0] >> 4 == MQTTPINGREQ) { - buffer[buffsize++] = MQTTPINGRESP << 4; - buffer[buffsize++] = 0x00; - } - if ((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE) { - buffer[buffsize++] = MQTTSUBACK << 4; // Just ack everything, we actually dont really care! - buffer[buffsize++] = 0x03; // Remaining length - buffer[buffsize++] = (uint8_t)inputString[2]; // Message ID MSB - buffer[buffsize++] = (uint8_t)inputString[3]; // Message ID LSB - buffer[buffsize++] = MQTTQOS0; // QOS level - } - if ((uint8_t)inputString[0] >> 4 == MQTTUNSUBSCRIBE) { - buffer[buffsize++] = MQTTUNSUBACK << 4; - buffer[buffsize++] = 0x02; // Remaining length - buffer[buffsize++] = (uint8_t)inputString[2]; // Message ID MSB - buffer[buffsize++] = (uint8_t)inputString[3]; // Message ID LSB - } - if ((uint8_t)inputString[0] >> 4 == MQTTDISCONNECT) { - MQTTClientConnected=false; // We lost connection! - } - if (buffsize > 0) { - dataCallback(buffer,&buffsize); - } - - // We publish everything we get, we dont care if its subscribed or not! - if ((uint8_t)inputString[0] >> 4 == MQTTPUBLISH || (MQTT_SEND_SUBSCRIPTION && (uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE)) { - buffer[0]= 0; - buffsize = 0; - // Cut out address and payload depending on message type. - if ((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE) { - strncat(buffer,inputString+6,inputString[5]); - } else { - strncat(buffer,inputString+4,inputString[3]); - } - - // TODO: Check if we should send ack or not. - for (str = strtok_r(buffer,"/",&p) ; str && i<4 ; str = strtok_r(NULL,"/",&p)) { - if (i == 0) { - if (strcmp_P(str,broker)!=0) { //look for MQTT_BROKER_PREFIX - return; //Message not for us or malformatted! - } - } else if (i==1) { - msg.destination = atoi(str); //NodeID - } else if (i==2) { - msg.sensor = atoi(str); //SensorID - } else if (i==3) { - char match=0; //SensorType - //strcpy(str,(char*)&str[2]); //Strip V_ - - for (uint8_t j=0; strcpy_P(convBuf, (char*)pgm_read_word(&(vType[j]))) ; j++) { - if (strcmp((char*)&str[2],convBuf)==0) { //Strip V_ and compare - match=j; - break; - } - if (j >= V_TOTAL) { // No match found! - match=V_TOTAL; // last item. - break; - } - } - msg.type = match; - } - i++; - } //Check if packge has payload - if ((uint8_t)inputString[1] > (uint8_t)(inputString[3]+2) && !((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE)) { - strcpy(convBuf,inputString+(inputString[3]+4)); - msg.set(convBuf); //Payload - } else { - msg.set(""); //No payload - } - txBlink(1); - if (!sendRoute(build(msg, GATEWAY_ADDRESS, msg.destination, msg.sensor, C_SET, msg.type, 0))) errBlink(1); - - } -} - -void MyMQTT::SendMQTT(MyMessage &msg) { - buffsize = 0; - if (!MQTTClientConnected) return; //We have no connections - return - if (msg.isAck()) { - Serial.println("msg is ack!"); - if (msg.sender==255 && mGetCommand(msg)==C_INTERNAL && msg.type==I_ID_REQUEST) { - // TODO: sending ACK request on id_response fucks node up. doesn't work. - // The idea was to confirm id and save to EEPROM_LATEST_NODE_ADDRESS. - } - } else { - // we have to check every message if its a newly assigned id or not. - // Ack on I_ID_RESPONSE does not work, and checking on C_PRESENTATION isn't reliable. - uint8_t newNodeID = loadState(EEPROM_LATEST_NODE_ADDRESS)+1; - if (newNodeID <= MQTT_FIRST_SENSORID) newNodeID = MQTT_FIRST_SENSORID; - if (msg.sender==newNodeID) { - saveState(EEPROM_LATEST_NODE_ADDRESS,newNodeID); - } - if (mGetCommand(msg)==C_INTERNAL) { - if (msg.type==I_CONFIG) { - txBlink(1); - if (!sendRoute(build(msg, GATEWAY_ADDRESS, msg.sender, 255, C_INTERNAL, I_CONFIG, 0).set("M"))) errBlink(1); - } else if (msg.type==I_ID_REQUEST && msg.sender==255) { - uint8_t newNodeID = loadState(EEPROM_LATEST_NODE_ADDRESS)+1; - if (newNodeID <= MQTT_FIRST_SENSORID) newNodeID = MQTT_FIRST_SENSORID; - if (newNodeID >= MQTT_LAST_SENSORID) return; // Sorry no more id's left :( - txBlink(1); - if (!sendRoute(build(msg, GATEWAY_ADDRESS, msg.sender, 255, C_INTERNAL, I_ID_RESPONSE, 0).set(newNodeID))) errBlink(1); - } - } else if (mGetCommand(msg)!=0) { - if (mGetCommand(msg)==3) msg.type=msg.type+(S_FIRSTCUSTOM-10); //Special message - - buffer[buffsize++] = MQTTPUBLISH << 4; // 0: - buffer[buffsize++] = 0x09; // 1: Remaining length with no payload, we'll set this later to correct value, buffsize -2 - buffer[buffsize++] = 0x00; // 2: Length MSB (Remaing length can never exceed ff,so MSB must be 0!) - buffer[buffsize++] = 0x08; // 3: Length LSB (ADDR), We'll set this later - if (msg.type > V_TOTAL) msg.type=V_TOTAL;// If type > defined types set to unknown. - strcpy_P(buffer+4, broker); - buffsize+=strlen_P(broker); - buffsize+=sprintf(&buffer[buffsize],"/%i/%i/V_%s",msg.sender,msg.sensor,getType(convBuf, &vType[msg.type])); - buffer[3]=buffsize-4; // Set correct address length on byte 4. -#ifdef DEBUG - Serial.println((char*)&buffer[4]); -#endif - msg.getString(convBuf); - for (uint8_t a=0; a -#include -#include +#include #include +#include +#include +#include "GatewayUtil.h" + // Use this if you have attached a Ethernet ENC28J60 shields //#include @@ -61,10 +65,15 @@ #define RADIO_CE_PIN 5 // radio chip enable #define RADIO_SPI_SS_PIN 6 // radio SPI serial select + #define RADIO_ERROR_LED_PIN 7 // Error led pin #define RADIO_RX_LED_PIN 8 // Receive led pin #define RADIO_TX_LED_PIN 9 // the PCB, on board LED + +MySensor gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN); + + #define IP_PORT 5003 // The port you want to open IPAddress myIp (192, 168, 178, 66); // Configure your static ip-address here @@ -76,22 +85,37 @@ byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // DEAD BEEF FEED // a R/W server on the port EthernetServer server = EthernetServer(IP_PORT); -// No blink or button functionality. Use the vanilla constructor. -MyGateway gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN, INCLUSION_MODE_TIME); - -// Uncomment this constructor if you have leds and include button attached to your gateway -//MyGateway gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN, INCLUSION_MODE_TIME, INCLUSION_MODE_PIN, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN); - char inputString[MAX_RECEIVE_LENGTH] = ""; // A string to hold incoming commands from serial/ethernet interface int inputPos = 0; + +void output(const char *fmt, ... ) { + va_list args; + va_start (args, fmt ); + vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args); + va_end (args); + Serial.print(serialBuffer); + server.write(serialBuffer); +} + + void setup() { // Initialize gateway at maximum PA level, channel 70 and callback for write operations - gw.begin(RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE, writeEthernet); + gw.begin(incomingMessage, 0, true, 0, RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE); Ethernet.begin(mac, myIp); + setupGateway(RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN, INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output); + + + // Add led timer interrupt + MsTimer2::set(300, ledTimersInterrupt); + MsTimer2::start(); + + // Add interrupt for inclusion button to pin + PCintPort::attachInterrupt(pinInclusion, startInclusionInterrupt, RISING); + // give the Ethernet interface a second to initialize delay(1000); @@ -100,14 +124,15 @@ void setup() server.begin(); } -// This will be called when data should be written to ethernet -void writeEthernet(char *writeBuffer) { - server.write(writeBuffer); -} - void loop() { + gw.process(); + + + checkButtonTriggeredInclusion(); + checkInclusionFinished(); + // if an incoming client connects, there will be // bytes available to read via the client object EthernetClient client = server.available(); @@ -128,7 +153,7 @@ void loop() // echo the string to the serial port Serial.print(inputString); - gw.parseAndSend(inputString); + parseAndSend(gw, inputString); // clear the string: inputPos = 0; @@ -143,7 +168,8 @@ void loop() } } } - gw.processRadioMessage(); } + + diff --git a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h new file mode 100644 index 0000000..ec4d128 --- /dev/null +++ b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h @@ -0,0 +1,262 @@ +#ifndef __GATEWAYUTIL_H__ +#define __GATEWAYUTIL_H__ + +#include + +#ifdef ARDUINO + + +uint8_t pinRx = 8; // Rx led pin +uint8_t pinTx = 9; // Tx led pin +uint8_t pinEr = 7; // Err led pin +uint8_t inclusionTime = 1; // Number of minutes inclusion mode is enabled +uint8_t pinInclusion = 3; // Input pin that should trigger inclusion mode + +#define MAX_RECEIVE_LENGTH 100 // Max buffersize needed for messages coming from controller +#define MAX_SEND_LENGTH 120 // Max buffersize needed for messages destined for controller + +volatile boolean buttonTriggeredInclusion; +volatile uint8_t countRx; +volatile uint8_t countTx; +volatile uint8_t countErr; +boolean inclusionMode; // Keeps track on inclusion mode +void (*serial)(const char *fmt, ... ); + +MyMessage msg; + +void setInclusionMode(boolean newMode); +void txBlink(uint8_t cnt); +void rxBlink(uint8_t cnt); +void errBlink(uint8_t cnt); + +char convBuf[MAX_PAYLOAD*2+1]; +char serialBuffer[MAX_SEND_LENGTH]; // Buffer for building string when sending data to vera +unsigned long inclusionStartTime; + +void setupGateway(uint8_t _rx, uint8_t _tx, uint8_t _er, uint8_t _inc, uint8_t _incTime, void (* _serial)(const char *, ... )) { + inclusionMode = 0; + buttonTriggeredInclusion = false; + serial = _serial; + + pinRx = _rx; + pinTx = _tx; + pinEr = _er; + pinInclusion = _inc; + inclusionTime = _incTime; + + countRx = 0; + countTx = 0; + countErr = 0; + + // Setup led pins + pinMode(pinRx, OUTPUT); + pinMode(pinTx, OUTPUT); + pinMode(pinEr, OUTPUT); + digitalWrite(pinRx, LOW); + digitalWrite(pinTx, LOW); + digitalWrite(pinEr, LOW); + + // Setup digital in that triggers inclusion mode + pinMode(pinInclusion, INPUT); + digitalWrite(pinInclusion, HIGH); + + // Set initial state of leds + digitalWrite(pinRx, HIGH); + digitalWrite(pinTx, HIGH); + digitalWrite(pinEr, HIGH); + +} + + + +void startInclusionInterrupt() { + buttonTriggeredInclusion = true; +} + +void incomingMessage(const MyMessage &message) { + if (mGetCommand(message) == C_PRESENTATION && inclusionMode) { + rxBlink(3); + } else { + rxBlink(1); + } + // Pass along the message from sensors to serial line + serial(PSTR("%d;%d;%d;%d;%d;%s\n"),message.sender, message.sensor, mGetCommand(message), mGetAck(message), message.type, message.getString(convBuf)); +} + + + +void checkButtonTriggeredInclusion() { + if (buttonTriggeredInclusion) { + // Ok, someone pressed the inclusion button on the gateway + // start inclusion mode for 1 munute. + serial(PSTR("0;0;%d;0;%d;Inclusion started by button.\n"), C_INTERNAL, I_LOG_MESSAGE); + buttonTriggeredInclusion = false; + setInclusionMode(true); + } +} + +void checkInclusionFinished() { + if (inclusionMode && millis()-inclusionStartTime>60000UL*inclusionTime) { + // inclusionTimeInMinutes minute(s) has passed.. stop inclusion mode + setInclusionMode(false); + } +} + +uint8_t h2i(char c) { + uint8_t i = 0; + if (c <= '9') + i += c - '0'; + else if (c >= 'a') + i += c - 'a' + 10; + else + i += c - 'A' + 10; + return i; +} + +void parseAndSend(MySensor gw, char *commandBuffer) { + boolean ok = false; + char *str, *p, *value=NULL; + uint8_t bvalue[MAX_PAYLOAD]; + uint8_t blen = 0; + int i = 0; + uint16_t destination = 0; + uint8_t sensor = 0; + uint8_t command = 0; + uint8_t type = 0; + uint8_t ack = 0; + + // Extract command data coming on serial line + for (str = strtok_r(commandBuffer, ";", &p); // split using semicolon + str && i < 6; // loop while str is not null an max 5 times + str = strtok_r(NULL, ";", &p) // get subsequent tokens + ) { + switch (i) { + case 0: // Radioid (destination) + destination = atoi(str); + break; + case 1: // Childid + sensor = atoi(str); + break; + case 2: // Message type + command = atoi(str); + break; + case 3: // Should we request ack from destination? + ack = atoi(str); + break; + case 4: // Data type + type = atoi(str); + break; + case 5: // Variable value + if (command == C_STREAM) { + blen = 0; + uint8_t val; + while (*str) { + val = h2i(*str++) << 4; + val += h2i(*str++); + bvalue[blen] = val; + blen++; + } + } else { + value = str; + // Remove ending carriage return character (if it exists) + uint8_t lastCharacter = strlen(value)-1; + if (value[lastCharacter] == '\r') + value[lastCharacter] = 0; + } + break; + } + i++; + } + + if (destination==GATEWAY_ADDRESS && command==C_INTERNAL) { + // Handle messages directed to gateway + if (type == I_VERSION) { + // Request for version + serial(PSTR("0;0;%d;0;%d;%s\n"), C_INTERNAL, I_VERSION, LIBRARY_VERSION); + } else if (type == I_INCLUSION_MODE) { + // Request to change inclusion mode + setInclusionMode(atoi(value) == 1); + } + } else { + txBlink(1); + msg.sender = GATEWAY_ADDRESS; + msg.destination = destination; + msg.sensor = sensor; + msg.type = type; + mSetCommand(msg,command); + mSetRequestAck(msg,ack?1:0); + mSetAck(msg,false); + if (command == C_STREAM) + msg.set(bvalue, blen); + else + msg.set(value); + ok = gw.sendRoute(msg); + if (!ok) { + errBlink(1); + } + } +} + + +void setInclusionMode(boolean newMode) { + if (newMode != inclusionMode) + inclusionMode = newMode; + // Send back mode change on serial line to ack command + serial(PSTR("0;0;%d;0;%d;%d\n"), C_INTERNAL, I_INCLUSION_MODE, inclusionMode?1:0); + + if (inclusionMode) { + inclusionStartTime = millis(); + } +} + + + + +void ledTimersInterrupt() { + if(countRx && countRx != 255) { + // switch led on + digitalWrite(pinRx, LOW); + } else if(!countRx) { + // switching off + digitalWrite(pinRx, HIGH); + } + if(countRx != 255) { countRx--; } + + if(countTx && countTx != 255) { + // switch led on + digitalWrite(pinTx, LOW); + } else if(!countTx) { + // switching off + digitalWrite(pinTx, HIGH); + } + if(countTx != 255) { countTx--; } + else if(inclusionMode) { countTx = 8; } + + if(countErr && countErr != 255) { + // switch led on + digitalWrite(pinEr, LOW); + } else if(!countErr) { + // switching off + digitalWrite(pinEr, HIGH); + } + if(countErr != 255) { countErr--; } + +} + +void rxBlink(uint8_t cnt) { + if(countRx == 255) { countRx = cnt; } +} +void txBlink(uint8_t cnt) { + if(countTx == 255 && !inclusionMode) { countTx = cnt; } +} +void errBlink(uint8_t cnt) { + if(countErr == 255) { countErr = cnt; } +} + + + +#else +#error This example is only for use on Arduino. +#endif // ARDUINO + +#endif diff --git a/libraries/MySensors/examples/MQTTGateway/GatewayUtil.h b/libraries/MySensors/examples/MQTTGateway/GatewayUtil.h new file mode 100644 index 0000000..58ff64a --- /dev/null +++ b/libraries/MySensors/examples/MQTTGateway/GatewayUtil.h @@ -0,0 +1,120 @@ +#ifndef __GATEWAYUTIL_H__ +#define __GATEWAYUTIL_H__ + +#include + +#ifdef ARDUINO + + +uint8_t pinRx = 8; // Rx led pin +uint8_t pinTx = 9; // Tx led pin +uint8_t pinEr = 7; // Err led pin + +#define MAX_RECEIVE_LENGTH 100 // Max buffersize needed for messages coming from controller +#define MAX_SEND_LENGTH 120 // Max buffersize needed for messages destined for controller + +volatile boolean buttonTriggeredInclusion; +volatile uint8_t countRx; +volatile uint8_t countTx; +volatile uint8_t countErr; + +MyMessage msg; + +void setInclusionMode(boolean newMode); +void txBlink(uint8_t cnt); +void rxBlink(uint8_t cnt); +void errBlink(uint8_t cnt); + +char convBuf[MAX_PAYLOAD*2+1]; +char serialBuffer[MAX_SEND_LENGTH]; // Buffer for building string when sending data to vera +unsigned long inclusionStartTime; + +void setupGateway(uint8_t _rx, uint8_t _tx, uint8_t _er, uint8_t _inc, uint8_t _incTime, void (* _serial)(const char *, ... )) { + inclusionMode = 0; + buttonTriggeredInclusion = false; + serial = _serial; + + pinRx = _rx; + pinTx = _tx; + pinEr = _er; + pinInclusion = _inc; + inclusionTime = _incTime; + + countRx = 0; + countTx = 0; + countErr = 0; + + // Setup led pins + pinMode(pinRx, OUTPUT); + pinMode(pinTx, OUTPUT); + pinMode(pinEr, OUTPUT); + digitalWrite(pinRx, LOW); + digitalWrite(pinTx, LOW); + digitalWrite(pinEr, LOW); + + + // Set initial state of leds + digitalWrite(pinRx, HIGH); + digitalWrite(pinTx, HIGH); + digitalWrite(pinEr, HIGH); + +} + + + +void startInclusionInterrupt() { + buttonTriggeredInclusion = true; +} + + + + + +void ledTimersInterrupt() { + if(countRx && countRx != 255) { + // switch led on + digitalWrite(pinRx, LOW); + } else if(!countRx) { + // switching off + digitalWrite(pinRx, HIGH); + } + if(countRx != 255) { countRx--; } + + if(countTx && countTx != 255) { + // switch led on + digitalWrite(pinTx, LOW); + } else if(!countTx) { + // switching off + digitalWrite(pinTx, HIGH); + } + if(countTx != 255) { countTx--; } + else if(inclusionMode) { countTx = 8; } + + if(countErr && countErr != 255) { + // switch led on + digitalWrite(RADIO_ERROR_LED_PIN, LOW); + } else if(!countErr) { + // switching off + digitalWrite(RADIO_ERROR_LED_PIN, HIGH); + } + if(countErr != 255) { countErr--; } + +} + +void rxBlink(uint8_t cnt) { + if(countRx == 255) { countRx = cnt; } +} +void txBlink(uint8_t cnt) { + if(countTx == 255 && !inclusionMode) { countTx = cnt; } +} +void errBlink(uint8_t cnt) { + if(countErr == 255) { countErr = cnt; } +} + + + +#else +#error This example is only for use on Arduino. +#endif // ARDUINO + +#endif diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index bbd44dd..388fba8 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -58,10 +58,14 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway #include #include -#include +#include #include +#include "MyMQTT.h" +#define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled +#define INCLUSION_MODE_PIN 3 // Digital pin used for inclusion mode button + // * Use this for IBOARD modded to use standard MISO/MOSI/SCK, see note *1 above! /* #define RADIO_CE_PIN 3 // radio chip enable @@ -72,6 +76,7 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway // * Use this for default configured pro mini / nano etc : ///* + #define RADIO_CE_PIN 5 // radio chip enable #define RADIO_SPI_SS_PIN 6 // radio SPI serial select #define RADIO_ERROR_LED_PIN 7 // Error led pin @@ -84,8 +89,28 @@ uint8_t TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You ////////////////////////////////////////////////////////////////// +MySensor gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN); EthernetServer server = EthernetServer(TCP_PORT); -MyMQTT gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN); +MyMessage msg; +char convBuf[MAX_PAYLOAD*2+1]; +char broker[] PROGMEM = MQTT_BROKER_PREFIX; +bool MQTTClientConnected = false; +uint8_t buffsize; +char buffer[MQTT_MAX_PACKET_SIZE]; +volatile uint8_t countRx; +volatile uint8_t countTx; +volatile uint8_t countErr; + + +void writeEthernet(const char *writeBuffer, uint8_t *writeSize) { +#ifdef TCPDUMP + Serial.print(">>"); + char buf[4]; + for (uint8_t a=0; a<*writeSize; a++) { sprintf(buf,"%02X ",(uint8_t)writeBuffer[a]); Serial.print(buf); } Serial.println(""); +#endif + server.write((const uint8_t *)writeBuffer, *writeSize); +} + void processEthernetMessages() { char inputString[MQTT_MAX_PACKET_SIZE] = ""; @@ -102,28 +127,284 @@ void processEthernetMessages() { char buf[4]; for (uint8_t a=0; a>"); - char buf[4]; - for (uint8_t a=0; a<*writeSize; a++) { sprintf(buf,"%02X ",(uint8_t)writeBuffer[a]); Serial.print(buf); } Serial.println(""); + + +void incomingMessage(const MyMessage &message) { + rxBlink(1); + sendMQTT(message); +} + + + +void setup() +{ + // Initialize gateway at maximum PA level, channel 70 and callback for write operations + gw.begin(incomingMessage, 0, true, 0, RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE); + + Ethernet.begin(TCP_MAC, TCP_IP); + + + countRx = 0; + countTx = 0; + countErr = 0; + + // Setup led pins + pinMode(RADIO_RX_LED_PIN, OUTPUT); + pinMode(RADIO_TX_LED_PIN, OUTPUT); + pinMode(RADIO_ERROR_LED_PIN, OUTPUT); + digitalWrite(RADIO_RX_LED_PIN, LOW); + digitalWrite(RADIO_TX_LED_PIN, LOW); + digitalWrite(RADIO_ERROR_LED_PIN, LOW); + + + // Set initial state of leds + digitalWrite(RADIO_RX_LED_PIN, HIGH); + digitalWrite(RADIO_TX_LED_PIN, HIGH); + digitalWrite(RADIO_ERROR_LED_PIN, HIGH); + + + // Add led timer interrupt + MsTimer2::set(300, ledTimersInterrupt); + MsTimer2::start(); + + + // give the Ethernet interface a second to initialize + delay(1000); + + // start listening for clients + server.begin(); + + Serial.println("Ok!"); +} + +void loop() +{ + gw.process(); + + processEthernetMessages(); +} + + + + + +inline MyMessage& build (MyMessage &msg, uint8_t destination, uint8_t sensor, uint8_t command, uint8_t type, bool enableAck) { + msg.destination = destination; + msg.sender = GATEWAY_ADDRESS; + msg.sensor = sensor; + msg.type = type; + mSetCommand(msg,command); + mSetRequestAck(msg,enableAck); + mSetAck(msg,false); + return msg; +} + +char *getType(char *b, const char **index) { + char *q = b; + char *p = (char *)pgm_read_word(index); + while (*q++ = pgm_read_byte(p++)); + *q=0; + return b; +} + +void processMQTTMessage(char *inputString, uint8_t inputPos) { + char *str, *p; + uint8_t i = 0; + buffer[0]= 0; + buffsize = 0; + + if ((uint8_t)inputString[0] >> 4 == MQTTCONNECT) { + buffer[buffsize++] = MQTTCONNACK << 4; + buffer[buffsize++] = 0x02; // Remaining length + buffer[buffsize++] = 0x00; // Connection accepted + buffer[buffsize++] = 0x00; // Reserved + MQTTClientConnected=true; // We have connection! + } + if ((uint8_t)inputString[0] >> 4 == MQTTPINGREQ) { + buffer[buffsize++] = MQTTPINGRESP << 4; + buffer[buffsize++] = 0x00; + } + if ((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE) { + buffer[buffsize++] = MQTTSUBACK << 4; // Just ack everything, we actually dont really care! + buffer[buffsize++] = 0x03; // Remaining length + buffer[buffsize++] = (uint8_t)inputString[2]; // Message ID MSB + buffer[buffsize++] = (uint8_t)inputString[3]; // Message ID LSB + buffer[buffsize++] = MQTTQOS0; // QOS level + } + if ((uint8_t)inputString[0] >> 4 == MQTTUNSUBSCRIBE) { + buffer[buffsize++] = MQTTUNSUBACK << 4; + buffer[buffsize++] = 0x02; // Remaining length + buffer[buffsize++] = (uint8_t)inputString[2]; // Message ID MSB + buffer[buffsize++] = (uint8_t)inputString[3]; // Message ID LSB + } + if ((uint8_t)inputString[0] >> 4 == MQTTDISCONNECT) { + MQTTClientConnected=false; // We lost connection! + } + if (buffsize > 0) { + writeEthernet(buffer,&buffsize); + } + + // We publish everything we get, we dont care if its subscribed or not! + if ((uint8_t)inputString[0] >> 4 == MQTTPUBLISH || (MQTT_SEND_SUBSCRIPTION && (uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE)) { + buffer[0]= 0; + buffsize = 0; + // Cut out address and payload depending on message type. + if ((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE) { + strncat(buffer,inputString+6,inputString[5]); + } else { + strncat(buffer,inputString+4,inputString[3]); + } + +#ifdef DEBUG + Serial.println(buffer); #endif - server.write((const uint8_t *)writeBuffer, *writeSize); -} + // TODO: Check if we should send ack or not. + for (str = strtok_r(buffer,"/",&p) ; str && i<4 ; str = strtok_r(NULL,"/",&p)) { + if (i == 0) { + if (strcmp_P(str,broker)!=0) { //look for MQTT_BROKER_PREFIX + return; //Message not for us or malformatted! + } + } else if (i==1) { + msg.destination = atoi(str); //NodeID + } else if (i==2) { + msg.sensor = atoi(str); //SensorID + } else if (i==3) { + char match=255; //SensorType +#ifdef MQTT_TRANSLATE_TYPES + for (uint8_t j=0; strcpy_P(convBuf, (char*)pgm_read_word(&(vType[j]))) ; j++) { + if (strcmp((char*)&str[2],convBuf)==0) { //Strip V_ and compare + match=j; + break; + } + if (j >= V_TOTAL) break; + } + +#endif + if ( atoi(str)!=0 || str=="0" ) { + match=atoi(str); + } + + if (match==255) { + match=V_UNKNOWN; + } + msg.type = match; + } + i++; + } //Check if packge has payload + if ((uint8_t)inputString[1] > (uint8_t)(inputString[3]+2) && !((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE)) { + strcpy(convBuf,inputString+(inputString[3]+4)); + msg.set(convBuf); //Payload + } else { + msg.set(""); //No payload + } + txBlink(1); + if (!gw.sendRoute(build(msg, msg.destination, msg.sensor, C_SET, msg.type, 0))) errBlink(1); -int main(void) { - init(); - Ethernet.begin(TCP_MAC, TCP_IP); - delay(1000); // Wait for Ethernet to get configured. - gw.begin(RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE, writeEthernet, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN); - server.begin(); - while (1) { - processEthernetMessages(); - gw.processRadioMessage(); } } + +void sendMQTT(const MyMessage &inMsg) { + MyMessage msg = inMsg; + buffsize = 0; + if (!MQTTClientConnected) return; //We have no connections - return + if (msg.isAck()) { +// if (msg.sender==255 && mGetCommand(msg)==C_INTERNAL && msg.type==I_ID_REQUEST) { +// TODO: sending ACK request on id_response fucks node up. doesn't work. +// The idea was to confirm id and save to EEPROM_LATEST_NODE_ADDRESS. +// } + } else { + // we have to check every message if its a newly assigned id or not. + // Ack on I_ID_RESPONSE does not work, and checking on C_PRESENTATION isn't reliable. + uint8_t newNodeID = gw.loadState(EEPROM_LATEST_NODE_ADDRESS)+1; + if (newNodeID <= MQTT_FIRST_SENSORID) newNodeID = MQTT_FIRST_SENSORID; + if (msg.sender==newNodeID) { + gw.saveState(EEPROM_LATEST_NODE_ADDRESS,newNodeID); + } + if (mGetCommand(msg)==C_INTERNAL) { + if (msg.type==I_CONFIG) { + txBlink(1); + if (!gw.sendRoute(build(msg, msg.sender, 255, C_INTERNAL, I_CONFIG, 0).set(MQTT_UNIT))) errBlink(1); + return; + } else if (msg.type==I_ID_REQUEST && msg.sender==255) { + uint8_t newNodeID = gw.loadState(EEPROM_LATEST_NODE_ADDRESS)+1; + if (newNodeID <= MQTT_FIRST_SENSORID) newNodeID = MQTT_FIRST_SENSORID; + if (newNodeID >= MQTT_LAST_SENSORID) return; // Sorry no more id's left :( + txBlink(1); + if (!gw.sendRoute(build(msg, msg.sender, 255, C_INTERNAL, I_ID_RESPONSE, 0).set(newNodeID))) errBlink(1); + return; + } + } + if (mGetCommand(msg)!=C_PRESENTATION) { + if (mGetCommand(msg)==C_INTERNAL) msg.type=msg.type+(S_FIRSTCUSTOM-10); //Special message + buffer[buffsize++] = MQTTPUBLISH << 4; // 0: + buffer[buffsize++] = 0x09; // 1: Remaining length with no payload, we'll set this later to correct value, buffsize -2 + buffer[buffsize++] = 0x00; // 2: Length MSB (Remaing length can never exceed ff,so MSB must be 0!) + buffer[buffsize++] = 0x08; // 3: Length LSB (ADDR), We'll set this later + strcpy_P(buffer+4, broker); + buffsize+=strlen_P(broker); +#ifdef MQTT_TRANSLATE_TYPES + if (msg.type > V_TOTAL) msg.type=V_UNKNOWN;// If type > defined types set to unknown. + buffsize+=sprintf(&buffer[buffsize],"/%i/%i/V_%s",msg.sender,msg.sensor,getType(convBuf, &vType[msg.type])); +#else + buffsize+=sprintf(&buffer[buffsize],"/%i/%i/%i",msg.sender,msg.sensor,msg.type); +#endif + buffer[3]=buffsize-4; // Set correct address length on byte 4. +#ifdef DEBUG + Serial.println((char*)&buffer[4]); +#endif + msg.getString(convBuf); + for (uint8_t a=0; a +Modified by Daniel Wiegert +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +version 2 as published by the Free Software Foundation. +*/ + +#ifdef DEBUG +#define TCPDUMP // Dump TCP packages +#endif + +#define MQTT_FIRST_SENSORID 20 // If you want manually configured nodes below this value. 255 = Disable +#define MQTT_LAST_SENSORID 254 // 254 is max! 255 reserved. +#define MQTT_BROKER_PREFIX "MyMQTT" // First prefix in MQTT tree, keep short! +#define MQTT_SEND_SUBSCRIPTION 1 // Send empty payload (request) to node upon MQTT client subscribe request. +// NOTE above : Beware to check if there is any length on payload in your incommingMessage code: +// Example: if (msg.type==V_LIGHT && strlen(msg.getString())>0) otherwise the code might do strange things. +#define MQTT_UNIT "M" // Select M for metric or I for imperial. +#define MQTT_TRANSLATE_TYPES // V_TYPE in address, Comment if you want all numbers (MyMQTT/01/01/01) + +////////////////////////////////////////////////////////////////// + +#define EEPROM_LATEST_NODE_ADDRESS ((uint8_t)EEPROM_LOCAL_CONFIG_ADDRESS) +#define MQTT_MAX_PACKET_SIZE 100 + +#define MQTTPROTOCOLVERSION 3 +#define MQTTCONNECT 1 // Client request to connect to Server +#define MQTTCONNACK 2 // Connect Acknowledgment +#define MQTTPUBLISH 3 // Publish message +#define MQTTPUBACK 4 // Publish Acknowledgment +#define MQTTPUBREC 5 // Publish Received (assured delivery part 1) +#define MQTTPUBREL 6 // Publish Release (assured delivery part 2) +#define MQTTPUBCOMP 7 // Publish Complete (assured delivery part 3) +#define MQTTSUBSCRIBE 8 // Client Subscribe request +#define MQTTSUBACK 9 // Subscribe Acknowledgment +#define MQTTUNSUBSCRIBE 10 // Client Unsubscribe request +#define MQTTUNSUBACK 11 // Unsubscribe Acknowledgment +#define MQTTPINGREQ 12 // PING Request +#define MQTTPINGRESP 13 // PING Response +#define MQTTDISCONNECT 14 // Client is Disconnecting +#define MQTTReserved 15 // Reserved + +#define MQTTQOS0 (0 << 1) +#define MQTTQOS1 (1 << 1) +#define MQTTQOS2 (2 << 1) + +#ifdef MQTT_TRANSLATE_TYPES + +char V_0[] PROGMEM = "TEMP"; //V_TEMP +char V_1[] PROGMEM = "HUM"; //V_HUM +char V_2[] PROGMEM = "LIGHT"; //V_LIGHT +char V_3[] PROGMEM = "DIMMER"; //V_DIMMER +char V_4[] PROGMEM = "PRESSURE"; //V_PRESSURE +char V_5[] PROGMEM = "FORECAST"; //V_FORECAST +char V_6[] PROGMEM = "RAIN"; //V_RAIN +char V_7[] PROGMEM = "RAINRATE"; //V_RAINRATE +char V_8[] PROGMEM = "WIND"; //V_WIND +char V_9[] PROGMEM = "GUST"; //V_GUST +char V_10[] PROGMEM = "DIRECTON"; //V_DIRECTON +char V_11[] PROGMEM = "UV"; //V_UV +char V_12[] PROGMEM = "WEIGHT"; //V_WEIGHT +char V_13[] PROGMEM = "DISTANCE"; //V_DISTANCE +char V_14[] PROGMEM = "IMPEDANCE"; //V_IMPEDANCE +char V_15[] PROGMEM = "ARMED"; //V_ARMED +char V_16[] PROGMEM = "TRIPPED"; //V_TRIPPED +char V_17[] PROGMEM = "WATT"; //V_WATT +char V_18[] PROGMEM = "KWH"; //V_KWH +char V_19[] PROGMEM = "SCENE_ON"; //V_SCENE_ON +char V_20[] PROGMEM = "SCENE_OFF"; //V_SCENE_OFF +char V_21[] PROGMEM = "HEATER"; //V_HEATER +char V_22[] PROGMEM = "HEATER_SW"; //V_HEATER_SW +char V_23[] PROGMEM = "LIGHT_LEVEL"; //V_LIGHT_LEVEL +char V_24[] PROGMEM = "VAR1"; //V_VAR1 +char V_25[] PROGMEM = "VAR2"; //V_VAR2 +char V_26[] PROGMEM = "VAR3"; //V_VAR3 +char V_27[] PROGMEM = "VAR4"; //V_VAR4 +char V_28[] PROGMEM = "VAR5"; //V_VAR5 +char V_29[] PROGMEM = "UP"; //V_UP +char V_30[] PROGMEM = "DOWN"; //V_DOWN +char V_31[] PROGMEM = "STOP"; //V_STOP +char V_32[] PROGMEM = "IR_SEND"; //V_IR_SEND +char V_33[] PROGMEM = "IR_RECEIVE"; //V_IR_RECEIVE +char V_34[] PROGMEM = "FLOW"; //V_FLOW +char V_35[] PROGMEM = "VOLUME"; //V_VOLUME +char V_36[] PROGMEM = "LOCK_STATUS"; //V_LOCK_STATUS +char V_37[] PROGMEM = "DUST_LEVEL"; //V_DUST_LEVEL +char V_38[] PROGMEM = "VOLTAGE"; //V_VOLTAGE +char V_39[] PROGMEM = "CURRENT"; //V_CURRENT +char V_40[] PROGMEM = ""; // +char V_41[] PROGMEM = ""; // +char V_42[] PROGMEM = ""; // +char V_43[] PROGMEM = ""; // +char V_44[] PROGMEM = ""; // +char V_45[] PROGMEM = ""; // +char V_46[] PROGMEM = ""; // +char V_47[] PROGMEM = ""; // +char V_48[] PROGMEM = ""; // +char V_49[] PROGMEM = ""; // +char V_50[] PROGMEM = ""; // +char V_51[] PROGMEM = ""; // +char V_52[] PROGMEM = ""; // +char V_53[] PROGMEM = ""; // +char V_54[] PROGMEM = ""; // +char V_55[] PROGMEM = ""; // +char V_56[] PROGMEM = ""; // +char V_57[] PROGMEM = ""; // +char V_58[] PROGMEM = ""; // +char V_59[] PROGMEM = ""; // +char V_60[] PROGMEM = "DEFAULT"; //Custom for MQTTGateway +char V_61[] PROGMEM = "SKETCH_NAME"; //Custom for MQTTGateway +char V_62[] PROGMEM = "SKETCH_VERSION"; //Custom for MQTTGateway +char V_63[] PROGMEM = "UNKNOWN"; //Custom for MQTTGateway + +////////////////////////////////////////////////////////////////// + +PROGMEM const char *vType[] = { + V_0, V_1, V_2, V_3, V_4, V_5, V_6, V_7, V_8, V_9, V_10, + V_11, V_12, V_13, V_14, V_15, V_16, V_17, V_18, V_19, V_20, + V_21, V_22, V_23, V_24, V_25, V_26, V_27, V_28, V_29, V_30, + V_31, V_32, V_33, V_34, V_35, V_36, V_37, V_38, V_39, V_40, + V_41, V_42, V_43, V_44, V_45, V_46, V_47, V_48, V_49, V_50, + V_51, V_52, V_53, V_54, V_55, V_56, V_57, V_58, V_59, V_60, + V_61, V_62, V_63 +}; + + + +#define S_FIRSTCUSTOM 60 +#define V_TOTAL (sizeof(vType)/sizeof(char *))-1 + +#endif + +#define S_FIRSTCUSTOM 60 +#define V_UNKNOWN 63 diff --git a/libraries/MySensors/MyMQTT.h b/libraries/MySensors/examples/MQTTGateway/MyMQTT.hx similarity index 100% rename from libraries/MySensors/MyMQTT.h rename to libraries/MySensors/examples/MQTTGateway/MyMQTT.hx diff --git a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h new file mode 100644 index 0000000..ec4d128 --- /dev/null +++ b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h @@ -0,0 +1,262 @@ +#ifndef __GATEWAYUTIL_H__ +#define __GATEWAYUTIL_H__ + +#include + +#ifdef ARDUINO + + +uint8_t pinRx = 8; // Rx led pin +uint8_t pinTx = 9; // Tx led pin +uint8_t pinEr = 7; // Err led pin +uint8_t inclusionTime = 1; // Number of minutes inclusion mode is enabled +uint8_t pinInclusion = 3; // Input pin that should trigger inclusion mode + +#define MAX_RECEIVE_LENGTH 100 // Max buffersize needed for messages coming from controller +#define MAX_SEND_LENGTH 120 // Max buffersize needed for messages destined for controller + +volatile boolean buttonTriggeredInclusion; +volatile uint8_t countRx; +volatile uint8_t countTx; +volatile uint8_t countErr; +boolean inclusionMode; // Keeps track on inclusion mode +void (*serial)(const char *fmt, ... ); + +MyMessage msg; + +void setInclusionMode(boolean newMode); +void txBlink(uint8_t cnt); +void rxBlink(uint8_t cnt); +void errBlink(uint8_t cnt); + +char convBuf[MAX_PAYLOAD*2+1]; +char serialBuffer[MAX_SEND_LENGTH]; // Buffer for building string when sending data to vera +unsigned long inclusionStartTime; + +void setupGateway(uint8_t _rx, uint8_t _tx, uint8_t _er, uint8_t _inc, uint8_t _incTime, void (* _serial)(const char *, ... )) { + inclusionMode = 0; + buttonTriggeredInclusion = false; + serial = _serial; + + pinRx = _rx; + pinTx = _tx; + pinEr = _er; + pinInclusion = _inc; + inclusionTime = _incTime; + + countRx = 0; + countTx = 0; + countErr = 0; + + // Setup led pins + pinMode(pinRx, OUTPUT); + pinMode(pinTx, OUTPUT); + pinMode(pinEr, OUTPUT); + digitalWrite(pinRx, LOW); + digitalWrite(pinTx, LOW); + digitalWrite(pinEr, LOW); + + // Setup digital in that triggers inclusion mode + pinMode(pinInclusion, INPUT); + digitalWrite(pinInclusion, HIGH); + + // Set initial state of leds + digitalWrite(pinRx, HIGH); + digitalWrite(pinTx, HIGH); + digitalWrite(pinEr, HIGH); + +} + + + +void startInclusionInterrupt() { + buttonTriggeredInclusion = true; +} + +void incomingMessage(const MyMessage &message) { + if (mGetCommand(message) == C_PRESENTATION && inclusionMode) { + rxBlink(3); + } else { + rxBlink(1); + } + // Pass along the message from sensors to serial line + serial(PSTR("%d;%d;%d;%d;%d;%s\n"),message.sender, message.sensor, mGetCommand(message), mGetAck(message), message.type, message.getString(convBuf)); +} + + + +void checkButtonTriggeredInclusion() { + if (buttonTriggeredInclusion) { + // Ok, someone pressed the inclusion button on the gateway + // start inclusion mode for 1 munute. + serial(PSTR("0;0;%d;0;%d;Inclusion started by button.\n"), C_INTERNAL, I_LOG_MESSAGE); + buttonTriggeredInclusion = false; + setInclusionMode(true); + } +} + +void checkInclusionFinished() { + if (inclusionMode && millis()-inclusionStartTime>60000UL*inclusionTime) { + // inclusionTimeInMinutes minute(s) has passed.. stop inclusion mode + setInclusionMode(false); + } +} + +uint8_t h2i(char c) { + uint8_t i = 0; + if (c <= '9') + i += c - '0'; + else if (c >= 'a') + i += c - 'a' + 10; + else + i += c - 'A' + 10; + return i; +} + +void parseAndSend(MySensor gw, char *commandBuffer) { + boolean ok = false; + char *str, *p, *value=NULL; + uint8_t bvalue[MAX_PAYLOAD]; + uint8_t blen = 0; + int i = 0; + uint16_t destination = 0; + uint8_t sensor = 0; + uint8_t command = 0; + uint8_t type = 0; + uint8_t ack = 0; + + // Extract command data coming on serial line + for (str = strtok_r(commandBuffer, ";", &p); // split using semicolon + str && i < 6; // loop while str is not null an max 5 times + str = strtok_r(NULL, ";", &p) // get subsequent tokens + ) { + switch (i) { + case 0: // Radioid (destination) + destination = atoi(str); + break; + case 1: // Childid + sensor = atoi(str); + break; + case 2: // Message type + command = atoi(str); + break; + case 3: // Should we request ack from destination? + ack = atoi(str); + break; + case 4: // Data type + type = atoi(str); + break; + case 5: // Variable value + if (command == C_STREAM) { + blen = 0; + uint8_t val; + while (*str) { + val = h2i(*str++) << 4; + val += h2i(*str++); + bvalue[blen] = val; + blen++; + } + } else { + value = str; + // Remove ending carriage return character (if it exists) + uint8_t lastCharacter = strlen(value)-1; + if (value[lastCharacter] == '\r') + value[lastCharacter] = 0; + } + break; + } + i++; + } + + if (destination==GATEWAY_ADDRESS && command==C_INTERNAL) { + // Handle messages directed to gateway + if (type == I_VERSION) { + // Request for version + serial(PSTR("0;0;%d;0;%d;%s\n"), C_INTERNAL, I_VERSION, LIBRARY_VERSION); + } else if (type == I_INCLUSION_MODE) { + // Request to change inclusion mode + setInclusionMode(atoi(value) == 1); + } + } else { + txBlink(1); + msg.sender = GATEWAY_ADDRESS; + msg.destination = destination; + msg.sensor = sensor; + msg.type = type; + mSetCommand(msg,command); + mSetRequestAck(msg,ack?1:0); + mSetAck(msg,false); + if (command == C_STREAM) + msg.set(bvalue, blen); + else + msg.set(value); + ok = gw.sendRoute(msg); + if (!ok) { + errBlink(1); + } + } +} + + +void setInclusionMode(boolean newMode) { + if (newMode != inclusionMode) + inclusionMode = newMode; + // Send back mode change on serial line to ack command + serial(PSTR("0;0;%d;0;%d;%d\n"), C_INTERNAL, I_INCLUSION_MODE, inclusionMode?1:0); + + if (inclusionMode) { + inclusionStartTime = millis(); + } +} + + + + +void ledTimersInterrupt() { + if(countRx && countRx != 255) { + // switch led on + digitalWrite(pinRx, LOW); + } else if(!countRx) { + // switching off + digitalWrite(pinRx, HIGH); + } + if(countRx != 255) { countRx--; } + + if(countTx && countTx != 255) { + // switch led on + digitalWrite(pinTx, LOW); + } else if(!countTx) { + // switching off + digitalWrite(pinTx, HIGH); + } + if(countTx != 255) { countTx--; } + else if(inclusionMode) { countTx = 8; } + + if(countErr && countErr != 255) { + // switch led on + digitalWrite(pinEr, LOW); + } else if(!countErr) { + // switching off + digitalWrite(pinEr, HIGH); + } + if(countErr != 255) { countErr--; } + +} + +void rxBlink(uint8_t cnt) { + if(countRx == 255) { countRx = cnt; } +} +void txBlink(uint8_t cnt) { + if(countTx == 255 && !inclusionMode) { countTx = cnt; } +} +void errBlink(uint8_t cnt) { + if(countErr == 255) { countErr = cnt; } +} + + + +#else +#error This example is only for use on Arduino. +#endif // ARDUINO + +#endif diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index 8c3a7dd..1d314d6 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Henrik Ekblad + * Copyright (C) 2013-2014 Henrik Ekblad * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -13,41 +13,83 @@ * * Wire connections (OPTIONAL): * - Inclusion button should be connected between digital pin 3 and GND - * - RX/TX/ERR leds need to be connected between +5V (anode) and digital ping 6/5/4 with resistor 270-330R in a series + * - RX/TX/ERR leds need to be connected between +5V (anode) and digital pin 6/5/4 with resistor 270-330R in a series * * LEDs (OPTIONAL): * - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved * - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly * - ERR (red) - fast blink on error during transmission error or recieve crc error */ + +#define NO_PORTB_PINCHANGES #include #include -#include #include +#include +#include +#include "GatewayUtil.h" + #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled -#define INCLUSION_MODE_PIN 3 // Digital pin used for inclusion mode button +#define INCLUSION_MODE_PIN 3 // Digital pin used for inclusion mode button +#define RADIO_ERROR_LED_PIN 4 // Error led pin +#define RADIO_RX_LED_PIN 6 // Receive led pin +#define RADIO_TX_LED_PIN 5 // the PCB, on board LED -MyGateway gw(DEFAULT_CE_PIN, DEFAULT_CS_PIN, INCLUSION_MODE_TIME, INCLUSION_MODE_PIN, 6, 5, 4); +MySensor gw(DEFAULT_CE_PIN, DEFAULT_CS_PIN); char inputString[MAX_RECEIVE_LENGTH] = ""; // A string to hold incoming commands from serial/ethernet interface int inputPos = 0; boolean commandComplete = false; // whether the string is complete +void parseAndSend(char *commandBuffer); + +void output(const char *fmt, ... ) { + va_list args; + va_start (args, fmt ); + vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args); + va_end (args); + Serial.print(serialBuffer); +} + + void setup() { - gw.begin(); + gw.begin(incomingMessage, 0, true, 0, RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE); + // Stetup pipes for radio library + gw.openReadingPipe(WRITE_PIPE, BASE_RADIO_ID); + gw.openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); + gw.startListening(); + + Serial.begin(BAUD_RATE); + + setupGateway(RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN, INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output); + + // Add led timer interrupt + MsTimer2::set(300, ledTimersInterrupt); + MsTimer2::start(); + + // Add interrupt for inclusion button to pin + PCintPort::attachInterrupt(pinInclusion, startInclusionInterrupt, RISING); + + + // Send startup log message on serial + serial(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"), C_INTERNAL, I_GATEWAY_READY); } void loop() { - gw.processRadioMessage(); + gw.process(); + + checkButtonTriggeredInclusion(); + checkInclusionFinished(); + if (commandComplete) { // A command wass issued from serial interface // We will now try to send it to the actuator - gw.parseAndSend(inputString); + parseAndSend(gw, inputString); commandComplete = false; inputPos = 0; } @@ -83,3 +125,4 @@ void serialEvent() { } + diff --git a/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.cpp b/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.cpp new file mode 100644 index 0000000..db49dce --- /dev/null +++ b/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.cpp @@ -0,0 +1,272 @@ +/* + ByteBuffer.cpp - A circular buffer implementation for Arduino + Created by Sigurdur Orn, July 19, 2010. + siggi@mit.edu + Updated by GreyGnome (aka Mike Schwager) Thu Feb 23 17:25:14 CST 2012 + added the putString() method and the fillError variable. + added the checkError() and resetError() methods. The checkError() method resets the fillError variable + to false as a side effect. + added the ByteBuffer(unsigned int buf_size) constructor. + added the init() method, and had the constructor call it automagically. + Also made the capacity, position, length, and fillError variables volatile, for safe use by interrupts. + */ + +#include "ByteBuffer.h" + +void ByteBuffer::init(){ + ByteBuffer::init(DEFAULTBUFSIZE); +} + +void ByteBuffer::init(unsigned int buf_length){ + data = (byte*)malloc(sizeof(byte)*buf_length); + capacity = buf_length; + position = 0; + length = 0; + fillError=false; +} + +void ByteBuffer::deAllocate(){ + free(data); +} + +void ByteBuffer::clear(){ + position = 0; + length = 0; +} + +void ByteBuffer::resetError(){ + fillError=false; +} + +boolean ByteBuffer::checkError(){ + /* + if (fillError) { + Serial.print("E: checkError: length "); + Serial.println(length, DEC); + } + */ + + boolean result=fillError; + fillError=false; + return(result); +} + +int ByteBuffer::getSize(){ + return length; +} + +int ByteBuffer::getCapacity(){ + return capacity; +} + +byte ByteBuffer::peek(unsigned int index){ + byte b = data[(position+index)%capacity]; + return b; +} + +uint8_t ByteBuffer::put(byte in){ + if(length < capacity){ + // save data byte at end of buffer + data[(position+length) % capacity] = in; + // increment the length + length++; + return 1; + } + // return failure + //Serial.print("E: put: "); + //Serial.println(length, DEC); + fillError=true; + return 0; +} + + +uint8_t ByteBuffer::putString(char *in){ + uint8_t count=0; + char *inString; + + inString=in; + uint8_t oldSREG = SREG; cli(); + while(length <= capacity){ + if (length == capacity) { + fillError=true; + return count; + } + // save data byte at end of buffer + data[(position+length) % capacity] = *inString; + // increment the length + length++; + inString++; + count++; + if (*inString == 0) { + if (count==0) fillError=true; // Serial.println("E: putString"); }; + SREG = oldSREG; // Restore register; reenables interrupts + return count; + } + } + SREG = oldSREG; // Restore register; reenables interrupts + return count; +} + +uint8_t ByteBuffer::putInFront(byte in){ + uint8_t oldSREG = SREG; cli(); + if(length < capacity){ + // save data byte at end of buffer + if( position == 0 ) + position = capacity-1; + else + position = (position-1)%capacity; + data[position] = in; + // increment the length + length++; + SREG = oldSREG; // Restore register; reenables interrupts + return 1; + } + // return failure + //Serial.println("E: putInFront"); + fillError=true; + SREG = oldSREG; // Restore register; reenables interrupts + return 0; +} + +byte ByteBuffer::get(){ + uint8_t oldSREG = SREG; cli(); + byte b = 0; + + if(length > 0){ + b = data[position]; + // move index down and decrement length + position = (position+1)%capacity; + length--; + } + SREG = oldSREG; // Restore register; reenables interrupts + return b; +} + +byte ByteBuffer::getFromBack(){ + byte b = 0; + if(length > 0){ + uint8_t oldSREG = SREG; cli(); + b = data[(position+length-1)%capacity]; + length--; + SREG = oldSREG; // Restore register; reenables interrupts + } + + return b; +} + +// +// Ints +// + +void ByteBuffer::putIntInFront(int in){ + byte *pointer = (byte *)∈ + putInFront(pointer[0]); + putInFront(pointer[1]); +} + +void ByteBuffer::putInt(int in){ + byte *pointer = (byte *)∈ + put(pointer[1]); + put(pointer[0]); +} + + +int ByteBuffer::getInt(){ + int ret; + byte *pointer = (byte *)&ret; + pointer[1] = get(); + pointer[0] = get(); + return ret; +} + +int ByteBuffer::getIntFromBack(){ + int ret; + byte *pointer = (byte *)&ret; + pointer[0] = getFromBack(); + pointer[1] = getFromBack(); + return ret; +} + +// +// Longs +// + +void ByteBuffer::putLongInFront(long in){ + byte *pointer = (byte *)∈ + putInFront(pointer[0]); + putInFront(pointer[1]); + putInFront(pointer[2]); + putInFront(pointer[3]); +} + +void ByteBuffer::putLong(long in){ + byte *pointer = (byte *)∈ + put(pointer[3]); + put(pointer[2]); + put(pointer[1]); + put(pointer[0]); +} + + +long ByteBuffer::getLong(){ + long ret; + byte *pointer = (byte *)&ret; + pointer[3] = get(); + pointer[2] = get(); + pointer[1] = get(); + pointer[0] = get(); + return ret; +} + +long ByteBuffer::getLongFromBack(){ + long ret; + byte *pointer = (byte *)&ret; + pointer[0] = getFromBack(); + pointer[1] = getFromBack(); + pointer[2] = getFromBack(); + pointer[3] = getFromBack(); + return ret; +} + + +// +// Floats +// + +void ByteBuffer::putFloatInFront(float in){ + byte *pointer = (byte *)∈ + putInFront(pointer[0]); + putInFront(pointer[1]); + putInFront(pointer[2]); + putInFront(pointer[3]); +} + +void ByteBuffer::putFloat(float in){ + byte *pointer = (byte *)∈ + put(pointer[3]); + put(pointer[2]); + put(pointer[1]); + put(pointer[0]); +} + +float ByteBuffer::getFloat(){ + float ret; + byte *pointer = (byte *)&ret; + pointer[3] = get(); + pointer[2] = get(); + pointer[1] = get(); + pointer[0] = get(); + return ret; +} + +float ByteBuffer::getFloatFromBack(){ + float ret; + byte *pointer = (byte *)&ret; + pointer[0] = getFromBack(); + pointer[1] = getFromBack(); + pointer[2] = getFromBack(); + pointer[3] = getFromBack(); + return ret; +} + + diff --git a/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.h b/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.h new file mode 100644 index 0000000..8916e58 --- /dev/null +++ b/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.h @@ -0,0 +1,104 @@ +/* + ByteBuffer.h - A circular buffer implementation for Arduino + Created by Sigurdur Orn, July 19, 2010. siggi@mit.edu + Updated by GreyGnome (aka Mike Schwager) Thu Feb 23 17:25:14 CST 2012 + added the putString() method and the fillError variable. + added the checkError() and resetError() methods. The checkError() method resets the fillError variable + to false as a side effect. + added the ByteBuffer(unsigned int buf_size) constructor. + added the init() method, and had the constructor call it automagically. + protected certain sections of the code with cli()/sei() calls, for safe use by interrupts. + Also made the capacity, position, length, and fillError variables volatile, for safe use by interrupts. + */ + +#ifndef ByteBuffer_h +#define ByteBuffer_h + +#if defined(ARDUINO) && ARDUINO >= 100 + #include +#else + #include +#endif +//#include + +#define DEFAULTBUFSIZE 32 +class ByteBuffer +{ +public: + ByteBuffer() { + init(); + }; + ByteBuffer(unsigned int buf_size) { + init(buf_size); + }; + + // This method initializes the datastore of the buffer to a certain size. + void init(unsigned int buf_size); + + // This method initializes the datastore of the buffer to the default size. + void init(); + + // This method resets the buffer into an original state (with no data) + void clear(); + + // This method resets the fillError variable to false. + void resetError(); + + // This method tells you if your buffer overflowed at some time since the last + // check. The error state will be reset to false. + boolean checkError(); + + // This releases resources for this buffer, after this has been called the buffer should NOT be used + void deAllocate(); + + // Returns how much space is used in the buffer + int getSize(); + + // Returns the maximum capacity of the buffer + int getCapacity(); + + // This method returns the byte that is located at index in the buffer but doesn't modify the buffer like the get methods (doesn't remove the retured byte from the buffer) + byte peek(unsigned int index); + + // + // Put methods, either a regular put in back or put in front + // + uint8_t putInFront(byte in); + uint8_t put(byte in); + uint8_t putString(char *in); + + void putIntInFront(int in); + void putInt(int in); + + void putLongInFront(long in); + void putLong(long in); + + void putFloatInFront(float in); + void putFloat(float in); + + // + // Get methods, either a regular get from front or from back + // + byte get(); + byte getFromBack(); + + int getInt(); + int getIntFromBack(); + + long getLong(); + long getLongFromBack(); + + float getFloat(); + float getFloatFromBack(); + +private: + byte* data; + + volatile unsigned int capacity; + volatile unsigned int position; + volatile unsigned int length; + volatile boolean fillError; +}; + +#endif + diff --git a/libraries/PinChangeInt/Examples/GetPSTR/GetPSTR.h b/libraries/PinChangeInt/Examples/GetPSTR/GetPSTR.h new file mode 100644 index 0000000..aaab06a --- /dev/null +++ b/libraries/PinChangeInt/Examples/GetPSTR/GetPSTR.h @@ -0,0 +1,21 @@ +#ifndef INCLUDE_GETPSTR +#define INCLUDE_GETPSTR + +#if defined(ARDUINO) && ARDUINO >= 100 + #include +#else + #include "pins_arduino.h" + #include "WProgram.h" + #include "wiring.h" +#endif + +#define getPSTR(s) pgmStrToRAM(PSTR(s)) + +char *_pstr_to_print; +char *pgmStrToRAM(PROGMEM char *theString) { + free(_pstr_to_print); + _pstr_to_print=(char *) malloc(strlen_P(theString)); + strcpy_P(_pstr_to_print, theString); + return (_pstr_to_print); +} +#endif diff --git a/libraries/PinChangeInt/Examples/PinChangeIntExample/PinChangeIntExample.pde b/libraries/PinChangeInt/Examples/PinChangeIntExample/PinChangeIntExample.pde new file mode 100644 index 0000000..2f254d4 --- /dev/null +++ b/libraries/PinChangeInt/Examples/PinChangeIntExample/PinChangeIntExample.pde @@ -0,0 +1,77 @@ +// PinChangeIntExample, version 1.1 Sun Jan 15 06:24:19 CST 2012 +// See the Wiki at http://code.google.com/p/arduino-pinchangeint/wiki for more information. +//-------- define these in your sketch, if applicable ---------------------------------------------------------- +// You can reduce the memory footprint of this handler by declaring that there will be no pin change interrupts +// on any one or two of the three ports. If only a single port remains, the handler will be declared inline +// reducing the size and latency of the handler. +//#define NO_PORTB_PINCHANGES // to indicate that port b will not be used for pin change interrupts +//#define NO_PORTC_PINCHANGES // to indicate that port c will not be used for pin change interrupts +// #define NO_PORTD_PINCHANGES // to indicate that port d will not be used for pin change interrupts +// if there is only one PCInt vector in use the code can be inlined +// reducing latency and code size +// define DISABLE_PCINT_MULTI_SERVICE below to limit the handler to servicing a single interrupt per invocation. +// #define DISABLE_PCINT_MULTI_SERVICE +//-------- define the above in your sketch, if applicable ------------------------------------------------------ +#include + +// This example demonstrates a configuration of 3 interrupting pins and 2 interrupt functions. +// All interrupts are serviced immediately, but one of the pins (pin 4) will show you immediately +// on the Terminal. The other function connected to 2 pins sets an array member that is queried in loop(). +// You can then query the array at your leisure. +// This makes loop timing non-critical. + +// Add more Pins at your leisure. +// For the Analog Input pins used as digital input pins, and you can use 14, 15, 16, etc. +// or you can use A0, A1, A2, etc. (the Arduino code comes with #define's +// for the Analog Input pins and will properly recognize e.g., pinMode(A0, INPUT); +#define PIN1 2 +#define PIN2 3 +#define PIN3 4 + +uint8_t latest_interrupted_pin; +uint8_t interrupt_count[20]={0}; // 20 possible arduino pins +void quicfunc() { + latest_interrupted_pin=PCintPort::arduinoPin; + interrupt_count[latest_interrupted_pin]++; +}; + +// You can assign any number of functions to any number of pins. +// How cool is that? +void pin3func() { + Serial.print("Pin "); Serial.print(PIN3, DEC); Serial.println("!"); +} + +void setup() { + pinMode(PIN1, INPUT); digitalWrite(PIN1, HIGH); + PCintPort::attachInterrupt(PIN1, &quicfunc, FALLING); // add more attachInterrupt code as required + pinMode(PIN2, INPUT); digitalWrite(PIN2, HIGH); + PCintPort::attachInterrupt(PIN2, &quicfunc, FALLING); + pinMode(PIN3, INPUT); digitalWrite(PIN3, HIGH); + PCintPort::attachInterrupt(PIN3, &pin3func, CHANGE); + Serial.begin(115200); + Serial.println("---------------------------------------"); +} + +uint8_t i; +void loop() { + uint8_t count; + Serial.print("."); + delay(1000); + for (i=0; i < 20; i++) { + if (interrupt_count[i] != 0) { + count=interrupt_count[i]; + interrupt_count[i]=0; + Serial.print("Count for pin "); + if (i < 14) { + Serial.print("D"); + Serial.print(i, DEC); + } else { + Serial.print("A"); + Serial.print(i-14, DEC); + } + Serial.print(" is "); + Serial.println(count, DEC); + } + } +} + diff --git a/libraries/PinChangeInt/Examples/PinChangeIntSpeedTest/PinChangeIntSpeedTest.pde b/libraries/PinChangeInt/Examples/PinChangeIntSpeedTest/PinChangeIntSpeedTest.pde new file mode 100644 index 0000000..f0ac0f2 --- /dev/null +++ b/libraries/PinChangeInt/Examples/PinChangeIntSpeedTest/PinChangeIntSpeedTest.pde @@ -0,0 +1,265 @@ +// PinChangeIntSpeedTest by GreyGnome aka Mike Schwager. Version numbers here refer to this sketch. +// Version 1.0 - initial version +// Version 1.1 - added code to test digitalRead() +// Version 1.2 - added new comments for the #define's for the NO_PORTx_PINCHANGES. +// Version 1.3 - includes cbiface.h with ooPinChangeInt, rather than cb.h +// Version 1.4 - testing version 2.10Beta with robtillaart's optimization +// Also added a #define/#undef INLINE_PCINTFUNC for inlining of the function called by the interrupt. +// Default: #undef for using the function as per usual. Changed PCIVERSION so that +// ooPinChangeInt starts at 1000 instead of 200. Modified the "Start" message to show "Start..", pause +// for 1 second, show "*\n" (where \n is a newline), pause for 1 second, then run the test. +// Version 1.4 - made this compatible with version 1.5 of PinChangeInt +// Version 1.5 - modified it to use #define OOPCIVERSION for ooPinChangeInt + +// This version number is for ooPinChangeInt +//#define OOPCIVERSION 1030 +#ifndef OOPCIVERSION +#define PCIVERSION 217 // 110 if using PinChangeInt-1.1, 120 for version 1.2 + // 1000 for ooPinChangeIntversion 1.00, 1001 for ooPinChangeInt version 1.01, etc. +#endif + +//-------- define these in your sketch, if applicable ---------------------------------------------------------- +// You can reduce the memory footprint of this handler by declaring that there will be no pin change interrupts +// on any one or two of the three ports. If only a single port remains, the handler will be declared inline +// reducing the size and latency of the handler. +#undef NO_PORTB_PINCHANGES // to indicate that port b will not be used for pin change interrupts +#undef NO_PORTC_PINCHANGES // to indicate that port c will not be used for pin change interrupts +// #define NO_PORTD_PINCHANGES // to indicate that port d will not be used for pin change interrupts +// You can reduce the code size by 20-50 bytes, and you can speed up the interrupt routine +// slightly by declaring that you don't care if the static variables PCintPort::pinState and/or +// PCintPort::arduinoPin are set and made available to your interrupt routine. +// #define NO_PIN_STATE // to indicate that you don't need the pinState +// #define NO_PIN_NUMBER // to indicate that you don't need the arduinoPin +// if there is only one PCInt vector in use the code can be inlined +// reducing latency and code size +// define DISABLE_PCINT_MULTI_SERVICE below to limit the handler to servicing a single interrupt per invocation. +//#define DISABLE_PCINT_MULTI_SERVICE +//-------- define the above in your sketch, if applicable ------------------------------------------------------ +#if defined(OOPCIVERSION) + #define LIBRARYUNDERTEST "ooPinChangeInt" + #include + #if PCIVERSION == 1001 + #include + #else + #include + #endif +#else + #define LIBRARYUNDERTEST "PinChangeInt" + #include +#endif + +#define SERIALSTUFF // undef to take out all serial statements. Default: #define for measuring time. +#undef MEMTEST // undef to take out memory tests. Default: #undef for measuring time. +#undef INLINE_PCINTFUNC // define to inline the function called from the interrupt. This should have no effect, + // because the compiler will store the registers upon calling the interrupt routine, just + // like calling a function. Still, we test all assumptions. +//----------------------- +// NOTE: BECAUSE OF COLLISIONS in these libraries, you CANNOT have both libraries: PinChangeInt +// and ooPinChangeInt in the libraries directory at the same time. That said, under UNIX-y operating +// systems, it's easy to move the library directory to a name such as "PinChangeInt-1.3", which the +// Arduino will not recognize, and then create a symbolic link when you want to use a library. Such as: +// cd ~/Documents/Arduino/libaries +// mv PinChangeInt PinChangeInt-1.30 +// mv ooPinChangeInt ooPinChangeInt-1.00 +// ln -s PinChangeInt-1.30 PinChangeInt + +#undef FLASH // to flash LED on pin 13 during test + +#ifdef MEMTEST +#include +#endif + +#define TEST 6 + +#if TEST == 1 +#define PTEST 2 // pin to trigger interrupt. pins 0 and 1 are used +#define PLOW 2 // by Serial, so steer clear of them! +#define PHIGH 2 // Interrupts are attached to these pins + +#elif TEST == 2 // see the #if TEST == 2 || TEST == 3 code, below +#define PTEST 2 +#define PLOW 2 +#define PHIGH 2 // need to attachInterrupt to 5 in the code + +#elif TEST == 3 // see the #if TEST == 2 || TEST == 3 code, below +#define PTEST 5 +#define PLOW 2 +#define PHIGH 2 // need to attachInterrupt to 5 in the code + +#elif TEST == 4 +#define PTEST 2 +#define PLOW 2 +#define PHIGH 5 + +#elif TEST == 5 +#define PTEST 3 +#define PLOW 2 +#define PHIGH 5 + +#elif TEST == 6 +#define PTEST 4 +#define PLOW 2 +#define PHIGH 5 + +#elif TEST == 7 +#define PTEST 5 +#define PLOW 2 +#define PHIGH 5 +#endif + +uint8_t qf0; + +#ifdef INLINE_PCINTFUNC +#define INLINE_PCINTFUNC inline +#else +#define INLINE_PCINTFUNC +#endif +INLINE_PCINTFUNC void quicfunc(); +void quicfunc() { + qf0=TCNT0; +} + +#if defined(OOPCIVERSION) +class speedy : public CallBackInterface +{ + public: + uint8_t id; + static uint8_t var0; + speedy () { id=0; }; + speedy (uint8_t _i): id(_i) {}; + + void cbmethod() { + speedy::var0=TCNT0; + //Serial.print("Speedy method "); // debugging + //Serial.println(id, DEC); + }; +}; +uint8_t speedy::var0=0; +#endif + +volatile uint8_t *led_port; +volatile uint8_t *pinT_OP; +volatile uint8_t *pinT_IP; +uint8_t led_mask, not_led_mask; +uint8_t pinT_M, not_pinT_M; +volatile uint8_t pintest, pinIntLow, pinIntHigh; +uint8_t totalpins; +#if defined(OOPCIVERSION) +speedy speedster[8]={speedy(0), speedy(1), speedy(2), speedy(3), speedy(4), speedy(5), speedy(6), speedy(7) }; +#endif +#ifdef MEMTEST +int freemem; +#endif + +int i=0; + +#define PINLED 13 +void setup() +{ +#ifdef SERIALSTUFF + Serial.begin(115200); Serial.println("---------------------------------------"); +#endif // SERIALSTUFF + // set up ports for trigger + pinMode(0, OUTPUT); digitalWrite(0, HIGH); + pinMode(1, OUTPUT); digitalWrite(1, HIGH); + pinMode(2, OUTPUT); digitalWrite(2, HIGH); + pinMode(3, OUTPUT); digitalWrite(3, HIGH); + pinMode(4, OUTPUT); digitalWrite(4, HIGH); + pinMode(5, OUTPUT); digitalWrite(5, HIGH); + pinMode(6, OUTPUT); digitalWrite(6, HIGH); + pinMode(7, OUTPUT); digitalWrite(7, HIGH); +#ifdef FLASH + led_port=portOutputRegister(digitalPinToPort(PINLED)); + led_mask=digitalPinToBitMask(PINLED); + not_led_mask=led_mask^0xFF; + pinMode(PINLED, OUTPUT); digitalWrite(PINLED, LOW); +#endif + // ***************************************************************************** + // set up ports for output ************ PIN TO TEST IS GIVEN HERE ************** + // ***************************************************************************** + pintest=PTEST; + pinIntLow=PLOW; pinIntHigh=PHIGH; // Interrupts are attached to these pins + // ***************************************************************************** + // ***************************************************************************** + pinT_OP=portOutputRegister(digitalPinToPort(pintest)); // output port + pinT_IP=portInputRegister(digitalPinToPort(pintest)); // input port + pinT_M=digitalPinToBitMask(pintest); // mask + not_pinT_M=pinT_M^0xFF; // not-mask + *pinT_OP|=pinT_M; + for (i=pinIntLow; i <= pinIntHigh; i++) { +#if defined(OOPCIVERSION) + PCintPort::attachInterrupt(i, &speedster[i], CHANGE); // C++ technique; v1.3 or better +#endif +#if defined(PCIVERSION) + PCintPort::attachInterrupt((uint8_t) i, &quicfunc, CHANGE); // C technique; v1.2 or earlier +#endif + } +#if TEST == 2 || TEST == 3 + i=5; totalpins=2; +#if defined(OOPCIVERSION) + PCintPort::attachInterrupt(i, &speedster[i], CHANGE); // C++ technique; v1.3 or better +#endif +#if defined(PCIVERSION) + PCintPort::attachInterrupt(i, &quicfunc, CHANGE); // C technique; v1.2 or earlier +#endif +#else + totalpins=pinIntHigh - pinIntLow + 1; +#endif + i=0; +} // end setup() + +uint8_t k=0; +unsigned long milliStart, milliEnd, elapsed; +void loop() { + k=0; + *pinT_OP|=pinT_M; // pintest to 1 +#ifdef SERIALSTUFF + Serial.print(LIBRARYUNDERTEST); Serial.print(" "); + Serial.print("TEST: "); Serial.print(TEST, DEC); Serial.print(" "); +#ifndef MEMTEST + Serial.print("test pin mask: "); Serial.print(pinT_M, HEX); + Serial.print(". Total of "); Serial.print(totalpins, DEC); Serial.println(" pins enabled."); +#endif +#ifdef MEMTEST + freemem=freeMemory(); Serial.print("Free memory: "); Serial.println(freemem, DEC); +#endif +#endif + delay(1000); + Serial.print("Start.."); + delay(1000); Serial.print("*"); + #ifdef FLASH + *led_port|=led_mask; + #endif + milliStart=millis(); + while (k < 10) { + i=0; + while (i < 10000) { + *pinT_OP&=not_pinT_M; // pintest to 0 ****************************** 16.8 us + *pinT_OP|=pinT_M; // pintest to 1 ****************************** ...to get here + i++; + } + k++; + } + milliEnd=millis(); + #ifdef FLASH + *led_port&=not_led_mask; + #endif + elapsed=milliEnd-milliStart; + #ifndef MEMTEST + Serial.print(" Elapsed: "); + Serial.println(elapsed, DEC); + #endif + #ifdef SERIALSTUFF + Serial.print("Interrupted pin: "); + #if defined(OOPCIVERSION) + Serial.println(speedster[pintest].id, DEC); + #else + Serial.println(PCintPort::arduinoPin, DEC); + #endif +#ifdef MEMTEST + freemem=freeMemory(); Serial.print("END-Free memory: "); Serial.println(freemem, DEC); +#endif +#endif + delay(500); +} + diff --git a/libraries/PinChangeInt/Examples/PinChangeIntTest/PinChangeIntTest.pde b/libraries/PinChangeInt/Examples/PinChangeIntTest/PinChangeIntTest.pde new file mode 100644 index 0000000..c8df127 --- /dev/null +++ b/libraries/PinChangeInt/Examples/PinChangeIntTest/PinChangeIntTest.pde @@ -0,0 +1,344 @@ +// PinChangeIntTest +// version 1.0 Wed Feb 15 07:25:09 CST 2012 +// Version 1.1 Fri Jun 22 19:10:50 CDT 2012 minor tweaks to eliminate compiler warnings. Also, there were bugfixes in ByteBuffer. +// I had some "cli()" without "sei()" in there. +// See the Wiki at http://code.google.com/p/arduino-pinchangeint/wiki for more information. +// This sketch requires the ByteBuffer library, which is found in the PinChangeInt zipfile. +//-------- define these in your sketch, if applicable ---------------------------------------------------------- +//-------- This must go ahead of the #include statement -------------------------------------------------------- +// You can reduce the memory footprint of this handler by declaring that there will be no pin change interrupts +// on any one or two of the three ports. If only a single port remains, the handler will be declared inline +// reducing the size and latency of the handler. +// #define NO_PORTB_PINCHANGES // to indicate that port b will not be used for pin change interrupts +// #define NO_PORTC_PINCHANGES // to indicate that port c will not be used for pin change interrupts +// #define NO_PORTD_PINCHANGES // to indicate that port d will not be used for pin change interrupts +// You can reduce the code size by 20-50 bytes, and you can speed up the interrupt routine +// slightly by declaring that you don't care if the static variables PCintPort::pinState and/or +// PCintPort::arduinoPin are set and made available to your interrupt routine. +// #define NO_PIN_STATE // to indicate that you don't need the pinState +// #define NO_PIN_NUMBER // to indicate that you don't need the arduinoPin +// if there is only one PCInt vector in use the code can be inlined +// reducing latency and code size +// define DISABLE_PCINT_MULTI_SERVICE below to limit the handler to servicing a single interrupt per invocation. +// #define DISABLE_PCINT_MULTI_SERVICE +// The following is intended for testing purposes. If defined, then a variable PCintPort::pinMode can be read +// in your interrupt subroutine. It is not defined by default: +// #define PINMODE +//-------- define the above in your sketch, if applicable ------------------------------------------------------ +#define PINMODE +#define FLASH +#include +#include + +// This example demonstrates a configuration of 6 interrupting pins and 3 interrupt functions. +// A variety of interrupting pins have been chosen, so as to test all PORTs on the Arduino. +// The pins are as follows: +#define tPIN1 2 // port D +#define tPIN2 3 +#define tPIN3 11 // Port B +#define tPIN4 12 +#define tPIN5 A3 // Port C, also can be given as "17" +#define tPIN6 A4 // starts and stops the count +// All pins send interrupts. Arduino pins 2 and A4 (tPIN1,6) interrupt on FALLING. +// Arduino pins 3 and 12 (tPIN2,4) interrupt on RISING. +// Arduino pins 11 and A3 (tPIN5) interrupts on CHANGE. +// quicfunc0 is attached to Arduino pins 2, 3, 11, and 12 (tPIN1-4) +// quicfunc1 is attached to Arduino pin A3 (tPIN5) +// quicfunc2 is attached to Arduino pin A4 (tPIN6). +// NOTE: +// For the Analog Input pins used as digital input pins, you can use numbers such as 14, 15, 16, etc. +// or you can use A0, A1, A2, etc. (the Arduino code comes with #define's for the Analog Input pin +// names and will properly recognize e.g., pinMode(A0, INPUT)); + +// HOW IT WORKS +// The interrupt on Arduino pin A4 (tPIN6) will, when triggered, start the counting of interrupts. +// The array interrupt_count0[20] is updated in the interrupts; each cell keeps track of the number +// of interrupts on one of the 20 available interrupt pins on the Arduino. Every second in the main +// loop the array is scanned and registered interrupts are reported for all pins interrupted since +// the previous second. If no interrupts, the output is quiet. + +// tPIN6 is special. Not only does it start the counting of the interrups, but it turns on and off +// interrupts on pins 2, 11, and A3/17 (tPIN1, tPIN3, tPIN5). All pins start by interrupting, but after +// the count is turned on and then turned off, the 3 pins are detached from interrupts. +// Everytime thereafter when the count is turned off the 3 pins are detached. They are reattached +// when turned on. + +// Output is copied to a buffer, because we can't do a Serial.print() statement in an interrupt +// routine. The main loop checks for entries in the buffer and prints them if found. +// Output looks like this: +// -F- - an interrupt triggered by a falling signal occurred. +// +R+ - an interrupt triggered by a rising signal occurred. +// *C* - an interrupt triggered by a change in signal occurred. +// f#p#-P# - f# shows the interrupt subroutine that was called: 0, 1, or 2 +// - p# shows the pin number that triggered the interrupt +// - P# shows the port that this pin number is attached to. 2 is PORTB, 3 is PORTC, 4 is PORTD + +// HOW TO CONNECT +// Each pin gets a momentary contact switch connected to it. One side of the switch should connect +// to ground. The other side of the switch connects to the Arduino pin. For my purposes, I am using +// two rotary encoders. Each encoder contains 3 switches. But 6 regular pushbuttons would work, too. + +/* WHAT TO LOOK FOR + Output is sent to the serial line, so the Arduino IDE's serial terminal should be opened. + Upon startup, press tPINS1-5. You will see output like this: +-F-f0p2-P4 (counting off) +..*C*f0p11-P2 (counting off) ++R+f0p3-P4 (counting off) + This shows that + 1. an interrupt was triggered on a falling signal (*F*). It called (f0) function 0, which is quicfunc0. + The triggering pin was (p2) Arduuino pin 2, which is on (P4) Port 4 (PORTD). Counting of this interrupt is + off, so you will not see any output from the main loop. + 2. Two dots appeared. Dots came from iterations of loop(), so these 2 dots show that the two interrupts happened 2 seconds apart. + 3. an interrupt was triggered on a change in signal (*C*). It called quicfunc0, from Arduino pin 11, on Port 2 (PORTB). + The interrupt was not counted. + 4. an interrupt was triggered on a rising signal (+R+). It called quicfunc0, from Arduino pin 3, on Purt 4 (PORTD). + The pin should have started out at the high level, so likely the signal fell during onother interrupt, and now + the rise has been caught. + + Now press the button attached to tPIN6 (in our case, A4 or D18). You will see something like this: +-F-START! f2p18-P3 +.Count for pin A4 is 1 + This shows that + 1. The counting machanism (START!) was triggered by a folling signal (-F-) on pin 18 (p18) which is in Port 3 (P3) (which == PORTC) and + function f2 was called (f2). + 2. A dot appeared, which came from loop() because a second passed. + 3. The count for p18 or A4 was displayed. + + Now you will see messages for all the pins that you manipulate, for example: +*C*f0p11-P2 ++R+f0p3-P4 +*C*f0p11-P2 ++R+f0p3-P4 +*C*f0p11-P2 +.Count for pin D3 is 6 +Count for pin D11 is 9 +.+R+f0p3-P4 +-F-f0p2-P4 +.Count for pin D2 is 1 +Count for pin D3 is 1 + These codes reflect the interrupts, as described above. This output will take place until you press tPIN6: +-F-f2: STOP! Counting off. +Interrupt OFF on tPIN1 (2) tPIN3 (11) tPIN5 (17) + Then you will see output like this: +.....................+R+f0p12-P2 (counting off) +.+R+f0p12-P2 (counting off) ++R+f0p12-P2 (counting off) ++R+f0p12-P2 (counting off) + and tPIN1, tPIN3, and tPIN5 will not trigger interrupts. +*/ +// NOTES +// Output overwrites: +// It's possible during moderately fast interrupts to see your print output get garbled; eg, +// +R+f0p12-P2 (+R+f0p12-P2 (counting +R+f0p12-P2 (cou+R+f0p12-P+R+f0p12 +// This is because the print of the buffer takes place inside a while loop, and it can +// be interrupted and new data inserted into the buffer at a midpoint of the buffer's text. +// Just by spinning my rotary encoders I can readily generate over 200 interrupts per second +// on a pin, which is easily fast enough to overrun Serial output at 115,200 bps. +// The lesson here? ...Interrupts are tricky, and interrupt service routines should be fast. +// Just sayin'. + +// Pins: +// We want to use pins from each of ports B, C and D. So choose wisely. Ports are shown in +// this diagram of the ATmega328P chip. PD0 means "Port D, pin 0". PC3 means "Port C, Pin 3", +// PB2 means "Port B, pin 2" and so on. The corresponding Arduino pins are in parentheses. +// So PB2 is Arduino pin D 10, for example. +/* + +-\/-+ + PC6 1| |28 PC5 (AI 5) + (D 0) PD0 2| |27 PC4 (AI 4) + (D 1) PD1 3| |26 PC3 (AI 3) + (D 2) PD2 4| |25 PC2 (AI 2) + PWM+ (D 3) PD3 5| |24 PC1 (AI 1) + (D 4) PD4 6| |23 PC0 (AI 0) + VCC 7| |22 GND + GND 8| |21 AREF + PB6 9| |20 AVCC + PB7 10| |19 PB5 (D 13) + PWM+ (D 5) PD5 11| |18 PB4 (D 12) + PWM+ (D 6) PD6 12| |17 PB3 (D 11) PWM + (D 7) PD7 13| |16 PB2 (D 10) PWM + (D 8) PB0 14| |15 PB1 (D 9) PWM + +----+ +*/ + +uint8_t pins[6]={ tPIN1, tPIN2, tPIN3, tPIN4, tPIN5, tPIN6 }; +uint8_t ports[6]={ 0, 0, 0, 0, 0, 0 }; + +uint8_t latest_interrupted_pin; +uint8_t interrupt_count[20]={0}; // 20 possible arduino pins +uint8_t port; +uint8_t mode; + +ByteBuffer printBuffer(80); +char charArray[16]; +char numBuffer[4] = { 0, 0, 0, 0 }; +uint8_t printFull=0; + +volatile boolean start=0; +volatile boolean initial=true; +long begintime=0; +long now=0; + +void uint8ToString(char *outString, uint8_t number) { + uint8_t hundreds=0; + uint8_t tens=0; + uint8_t ones=0; + + while (number >= 100 ) { + hundreds++; + number-=100; + } + while (number >= 10 ) { + tens++; + number-=10; + } + ones=number; + ones+=48; + if (hundreds > 0) { hundreds+=48; tens+=48; outString[0]=hundreds; outString[1]=tens; outString[2]=ones; outString[3]=0; } + else if (tens > 0) { tens+=48; outString[0]=tens; outString[1]=ones; outString[2]=0; } + else { outString[0]=ones; outString[1]=0; }; +} + +void showMode() { + switch (mode) { + case FALLING: + printBuffer.putString((char *) "-F-"); + break; + case RISING: + printBuffer.putString((char *) "+R+"); + break; + case CHANGE: + printBuffer.putString((char *) "*C*"); + break; + } +} + +void quicfunc0() { + latest_interrupted_pin=PCintPort::arduinoPin; + mode=PCintPort::pinmode; + showMode(); + if (start==1) { + interrupt_count[latest_interrupted_pin]++; + } + uint8ToString(numBuffer, latest_interrupted_pin); + printBuffer.putString((char *) "f0p"); printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); + uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); + printBuffer.putString(numBuffer); + if (start !=1) printBuffer.putString((char *) " (counting off)"); + printBuffer.putString((char *) "\n"); +}; + +void quicfunc1() { + latest_interrupted_pin=PCintPort::arduinoPin; + mode=PCintPort::pinmode; + showMode(); + if (start==1) { + interrupt_count[latest_interrupted_pin]++; + } + uint8ToString(numBuffer, latest_interrupted_pin); + printBuffer.putString((char *) "f1p"); printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); + uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); + printBuffer.putString(numBuffer); + if (start !=1) printBuffer.putString((char *) " (counting off)"); + printBuffer.putString((char *) "\n"); +}; + +void quicfunc2() { + latest_interrupted_pin=PCintPort::arduinoPin; + mode=PCintPort::pinmode; + showMode(); + if (start == 1) { + printBuffer.putString((char *) "f2: STOP! Counting off.\n"); + printBuffer.putString((char *) "Interrupt OFF on tPIN1 ("); uint8ToString(numBuffer, tPIN1), printBuffer.putString(numBuffer); + printBuffer.putString((char *) ") tPIN3 (");uint8ToString(numBuffer, tPIN3), printBuffer.putString(numBuffer); + printBuffer.putString((char *) ") tPIN5 (");uint8ToString(numBuffer, tPIN5), printBuffer.putString(numBuffer); + printBuffer.putString((char *) ")\n"); + PCintPort::detachInterrupt(tPIN1); PCintPort::detachInterrupt(tPIN3); PCintPort::detachInterrupt(tPIN5); + start=0; + } else { + start=1; + interrupt_count[latest_interrupted_pin]++; + printBuffer.putString((char *) "START! f2p"); + uint8ToString(numBuffer, latest_interrupted_pin); + printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); + uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); + printBuffer.putString(numBuffer); printBuffer.putString((char *) "\n"); + if (! initial) { + PCintPort::attachInterrupt(tPIN1, &quicfunc0, FALLING); + PCintPort::attachInterrupt(tPIN3, &quicfunc0, CHANGE); + PCintPort::attachInterrupt(tPIN5, &quicfunc1, CHANGE); + } else { + initial=false; + } + } +}; + +uint8_t i; +void setup() { + Serial.begin(115200); + delay(250); + Serial.println("Test"); + delay(500); + for (i=0; i < 7; i++) { + pinMode(pins[i], INPUT); digitalWrite(pins[i], HIGH); + ports[i]=digitalPinToPort(pins[i]); + switch (pins[i]) { + case tPIN1: + PCintPort::attachInterrupt(pins[i], &quicfunc0, FALLING); + break; + case tPIN3: + PCintPort::attachInterrupt(pins[i], &quicfunc0, CHANGE); + break; + case tPIN2: + case tPIN4: + PCintPort::attachInterrupt(pins[i], &quicfunc0, RISING); + break; + case tPIN5: + PCintPort::attachInterrupt(pins[i], &quicfunc1, CHANGE); + break; + case tPIN6: + PCintPort::attachInterrupt(pins[i], &quicfunc2, FALLING); + break; + } + } + //Serial.println(printBuffer.getCapacity(), DEC); + //Serial.println("*---------------------------------------*"); + Serial.print("*---*"); + delay(250); + begintime=millis(); +} + +void loop() { + now=millis(); + uint8_t count; + char outChar; + // uint8_t bufsize; + //if (printBuffer.getSize() != 0) { Serial.print("SZ:"); Serial.println (printBuffer.getSize(), DEC); }; + //bufsize=printBuffer.getSize(); + //if (bufsize > 0) { Serial.print("S:"); Serial.println(bufsize); } + while ((outChar=(char)printBuffer.get()) != 0) Serial.print(outChar); + if ((now - begintime) > 1000) { + Serial.print("."); + if (printBuffer.checkError()) { + Serial.println("NOTICE: Some output lost due to filled buffer."); + } + for (i=0; i < 20; i++) { + if (interrupt_count[i] != 0) { + count=interrupt_count[i]; + interrupt_count[i]=0; + Serial.print("Count for pin "); + if (i < 14) { + Serial.print("D"); + Serial.print(i, DEC); + } else { + Serial.print("A"); + Serial.print(i-14, DEC); + } + Serial.print(" is "); + Serial.println(count, DEC); + } + } + begintime=millis(); + } +} + diff --git a/libraries/PinChangeInt/Examples/PinChangeIntTest2/PinChangeIntTest2.ino b/libraries/PinChangeInt/Examples/PinChangeIntTest2/PinChangeIntTest2.ino new file mode 100644 index 0000000..aec34c4 --- /dev/null +++ b/libraries/PinChangeInt/Examples/PinChangeIntTest2/PinChangeIntTest2.ino @@ -0,0 +1,275 @@ +//#define DISABLE_PCINT_MULTI_SERVICE +#define PINMODE +#define FLASH +#include +#include +#include + +// This example demonstrates a configuration of 6 interrupting pins and 3 interrupt functions. +// A variety of interrupting pins have been chosen, so as to test all PORTs on the Arduino. +// The pins are as follows: +#define tPIN1 2 // port D +#define tPIN2 3 +#define tPIN3 11 // Port B +#define tPIN4 12 +#define tPIN5 A3 // Port C, also can be given as "17" +#define tPIN6 A4 // starts and stops the count + +uint8_t pins[6]={ tPIN1, tPIN2, tPIN3, tPIN4, tPIN5, tPIN6 }; +uint8_t ports[6]={ 0, 0, 0, 0, 0, 0 }; + +uint8_t latest_interrupted_pin; +uint8_t interrupt_count[20]={0}; // 20 possible arduino pins +uint8_t port; +uint8_t mode; + +ByteBuffer printBuffer(200); +char charArray[16]; +char numBuffer[5] = { 0, 0, 0, 0, 0 }; +uint8_t printFull=0; + +volatile boolean start=0; +volatile boolean initial=true; +long begintime=0; +long now=0; + +void uint8ToHexString(char *outString, uint8_t theByte) { + outString[0]='0'; outString[1]='x'; + uint8_t hinybble=theByte>>4; + uint8_t lonybble=theByte & 0x0F; + if (hinybble < 0x0a) outString[2]=hinybble+48; + else outString[2]=hinybble+55; + if (lonybble < 0x0a) outString[3]=lonybble+48; + else outString[3]=lonybble+55; + outString[4]=0; +} + +void uint8ToString(char *outString, uint8_t number) { + uint8_t hundreds=0; + uint8_t tens=0; + uint8_t ones=0; + + while (number >= 100 ) { + hundreds++; + number-=100; + } + while (number >= 10 ) { + tens++; + number-=10; + } + ones=number; + ones+=48; + if (hundreds > 0) { hundreds+=48; tens+=48; outString[0]=hundreds; outString[1]=tens; outString[2]=ones; outString[3]=0; } + else if (tens > 0) { tens+=48; outString[0]=tens; outString[1]=ones; outString[2]=0; } + else { outString[0]=ones; outString[1]=0; }; +} + +void showMode() { + switch (mode) { + case FALLING: + printBuffer.putString(getPSTR("-F-")); + break; + case RISING: + printBuffer.putString(getPSTR("+R+")); + break; + case CHANGE: + printBuffer.putString(getPSTR("*C*")); + break; + } +} + +/* +void quicfunc0() { + latest_interrupted_pin=PCintPort::arduinoPin; + mode=PCintPort::pinmode; + showMode(); + if (start==1) { + interrupt_count[latest_interrupted_pin]++; + } + uint8ToString(numBuffer, latest_interrupted_pin); + printBuffer.putString((char *) "f0p"); printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); + uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); + printBuffer.putString(numBuffer); + if (start !=1) printBuffer.putString(getPSTR(" no count")); + printBuffer.putString((char *) "\n"); +}; + +void quicfunc1() { + latest_interrupted_pin=PCintPort::arduinoPin; + mode=PCintPort::pinmode; + showMode(); + if (start==1) { + interrupt_count[latest_interrupted_pin]++; + } + uint8ToString(numBuffer, latest_interrupted_pin); + printBuffer.putString(getPSTR("f1p")); printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); + uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); + printBuffer.putString(numBuffer); + if (start !=1) printBuffer.putString(getPSTR(" (counting off)")); + printBuffer.putString((char *) "\n"); +}; +*/ + +void quicfunc2() { + //*led_port|=led_mask; + //*led_port&=not_led_mask; // 2 micros to here (ie, 2 micros used to push registers and call subroutine) + latest_interrupted_pin=PCintPort::arduinoPin; + mode=PCintPort::pinmode; + showMode(); + *led_port|=led_mask; // 73 micros to get here from above. Used in "Rigol Timing Example" + *led_port&=not_led_mask; + //uint8ToString(numBuffer, PCintPort::s_count); printBuffer.putString(numBuffer); + *led_port|=led_mask; // 73 micros to get here from above. Second pulse in "Rigol Timing Example" + *led_port&=not_led_mask; + printBuffer.putString(getPSTR(" f2: P"));/* + uint8ToHexString(numBuffer, *portInputRegister(3)); printBuffer.putString(numBuffer);// C port + printBuffer.putString(getPSTR(" pin:")); uint8ToString(numBuffer, latest_interrupted_pin); printBuffer.putString(numBuffer); + printBuffer.putString(getPSTR(" c")); uint8ToHexString(numBuffer, PCintPort::curr); printBuffer.putString(numBuffer); + printBuffer.putString(getPSTR(" l")); uint8ToHexString(numBuffer, PCintPort::s_lastPinView); printBuffer.putString(numBuffer); + printBuffer.putString(getPSTR(" r")); uint8ToHexString(numBuffer, PCintPort::s_portRisingPins); printBuffer.putString(numBuffer); + printBuffer.putString(getPSTR(" f")); uint8ToHexString(numBuffer, PCintPort::s_portFallingPins); printBuffer.putString(numBuffer); + printBuffer.putString(getPSTR(" m")); uint8ToHexString(numBuffer, PCintPort::s_pmask); printBuffer.putString(numBuffer); + printBuffer.putString(getPSTR(" P")); printBuffer.put(PCintPort::s_PORT); printBuffer.putString("\r\n"); + printBuffer.putString(getPSTR("cp")); uint8ToHexString(numBuffer, PCintPort::s_changedPins); printBuffer.putString(numBuffer); + printBuffer.putString(getPSTR(" cXORlpv")); uint8ToHexString(numBuffer, PCintPort::s_currXORlastPinView); printBuffer.putString(numBuffer); + printBuffer.putString(getPSTR(" rp_nCurr")); uint8ToHexString(numBuffer, PCintPort::s_portRisingPins_nCurr); printBuffer.putString(numBuffer); + printBuffer.putString(getPSTR(" fp_nNCurr")); uint8ToHexString(numBuffer, PCintPort::s_portFallingPins_nNCurr); printBuffer.putString(numBuffer); + */printBuffer.putString("\r\n"); + if (PCintPort::pcint_multi > 0) { + printBuffer.putString("MULTI!\n"); PCintPort::pcint_multi=0; + } + if (PCintPort::PCIFRbug > 0) { printBuffer.putString("ERROR: BUG- PCIFR should be reset!"); PCintPort::PCIFRbug=0; } + //s_registers, if it existed, could be used to keep a running queue of the latest interrupts that have + //been serviced by the PCint(). But generally I don't think it's necessary for debugging at this point (famous last words?) + /*if (PCintPort::s_count > 2) { + for (uint8_t i=0; i < PCintPort::s_count; i++) { + uint8ToHexString(numBuffer, PCintPort::s_registers[i]); printBuffer.putString(numBuffer); printBuffer.putString(" "); + } + } + PCintPort::s_count=0;*/ + /* + if (start == 1) { + printBuffer.putString(getPSTR("STOP Count off\n")); + printBuffer.putString(getPSTR("Intr OFF: (")); uint8ToString(numBuffer, tPIN1), printBuffer.putString(numBuffer); + printBuffer.putString((char *) " "); uint8ToString(numBuffer, tPIN3), printBuffer.putString(numBuffer); + printBuffer.putString((char *) " "); uint8ToString(numBuffer, tPIN5), printBuffer.putString(numBuffer); + printBuffer.putString((char *) ")\n"); + PCintPort::detachInterrupt(tPIN1); PCintPort::detachInterrupt(tPIN3); PCintPort::detachInterrupt(tPIN5); + start=0; + } else { + start=1; + interrupt_count[latest_interrupted_pin]++; + printBuffer.putString(getPSTR("START! p")); + uint8ToString(numBuffer, latest_interrupted_pin); + printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); + // MIKE put the REAL PORT HERE + uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); + printBuffer.putString(numBuffer); printBuffer.putString((char *) "\n"); + if (! initial) { + PCintPort::attachInterrupt(tPIN1, &quicfunc0, FALLING); + PCintPort::attachInterrupt(tPIN3, &quicfunc0, CHANGE); + PCintPort::attachInterrupt(tPIN5, &quicfunc1, CHANGE); + } else { + initial=false; + } + }*/ +}; + +uint8_t i; +char hexBuffer[5]; +void setup() { + int8_t returncode=1; + Serial.begin(115200); + Serial.println("Test"); + delay(500); + for (i=5; i < 6; i++) { + pinMode(pins[i], INPUT); digitalWrite(pins[i], HIGH); + ports[i]=digitalPinToPort(pins[i]); + switch (pins[i]) { + /*case tPIN1: + #if PCINT_VERSION > 2100 + returncode=PCintPort::attachInterrupt(pins[i], &quicfunc0, FALLING); + #else + PCintPort::attachInterrupt(pins[i], &quicfunc0, FALLING); + #endif + Serial.println(getPSTR("FIRST FAILURE OK.")); + break; + case tPIN3: + #if PCINT_VERSION > 2100 + returncode=PCintPort::attachInterrupt(pins[i], &quicfunc0, CHANGE); + #else + PCintPort::attachInterrupt(pins[i], &quicfunc0, CHANGE); + #endif + break; + case tPIN2: + case tPIN4: + #if PCINT_VERSION > 2100 + returncode=PCintPort::attachInterrupt(pins[i], &quicfunc0, RISING); + #else + PCintPort::attachInterrupt(pins[i], &quicfunc0, RISING); + #endif + break; + case tPIN5: + #if PCINT_VERSION > 2100 + returncode=PCintPort::attachInterrupt(pins[i], &quicfunc1, CHANGE); + #else + PCintPort::attachInterrupt(pins[i], &quicfunc1, CHANGE); + #endif + break;*/ + case tPIN6: + #if PCINT_VERSION > 2100 + returncode=PCintPort::attachInterrupt(pins[i], &quicfunc2, FALLING); + #else + PCintPort::attachInterrupt(pins[i], &quicfunc2, FALLING); + #endif + break; + } + #if PCINT_VERSION > 2100 + Serial.print(getPSTR("setup(): Interrupt attach ")); + if (returncode != 1) Serial.print(getPSTR("unsuccessful ")); + else Serial.print(getPSTR("GOOD ")); + Serial.print(pins[i], DEC); + Serial.print(getPSTR(":pin, code: ")); Serial.println(returncode, DEC); + #endif + } + //Serial.println(printBuffer.getCapacity(), DEC); + //Serial.println("*---------------------------------------*"); + Serial.print("*---*"); + delay(250); + begintime=millis(); +} + +void loop() { + now=millis(); + uint8_t count; + char outChar; + // uint8_t bufsize; + //if (printBuffer.getSize() != 0) { Serial.print("SZ:"); Serial.println (printBuffer.getSize(), DEC); }; + //bufsize=printBuffer.getSize(); + //if (bufsize > 0) { Serial.print("S:"); Serial.println(bufsize); } + while ((outChar=(char)printBuffer.get()) != 0) Serial.print(outChar); + if ((now - begintime) > 1000) { + Serial.print("."); + if (printBuffer.checkError()) { + Serial.println(getPSTR("!Some output lost due to full buffer!")); + } + for (i=0; i < 20; i++) { + if (interrupt_count[i] != 0) { + count=interrupt_count[i]; + interrupt_count[i]=0; + Serial.print(getPSTR("Count for pin ")); + if (i < 14) { + Serial.print("D"); + Serial.print(i, DEC); + } else { + Serial.print("A"); + Serial.print(i-14, DEC); + } + Serial.print(" is "); + Serial.println(count, DEC); + } + } + begintime=millis(); + } +} + diff --git a/libraries/MySensors/utility/PinChangeInt.h b/libraries/PinChangeInt/PinChangeInt.h similarity index 100% rename from libraries/MySensors/utility/PinChangeInt.h rename to libraries/PinChangeInt/PinChangeInt.h diff --git a/libraries/PinChangeInt/RELEASE_NOTES b/libraries/PinChangeInt/RELEASE_NOTES new file mode 100644 index 0000000..635e4f8 --- /dev/null +++ b/libraries/PinChangeInt/RELEASE_NOTES @@ -0,0 +1,332 @@ +****************************************************************************** + + PinChangeInt + ---- RELEASE NOTES --- + +Version 2.19 (beta) Tue Nov 20 07:33:37 CST 2012 +SANGUINO SUPPORT! ...And Mioduino! +...The ATmega644 chip is so cool, how can I not? 4 full ports of Pin Change Interrupt bliss! 32 i/o pins! 64k Flash! 4k RAM! Well I wish I had one. That said, Sanguino users, PLEASE send in your bug or bliss reports! Your interrupt-loving brethren and sistren are depending on you, so I can assure everyone that my changes work on that platform. Thanks. + +Modified the addPin() method to save 12 bytes; thanks again robtilllart! + if (firstPin != NULL) { + tmp=firstPin; + do { + if (tmp->arduinoPin == arduinoPin) { enable(tmp, userFunc, mode); return(0); } + if (tmp->next == NULL) break; + tmp=tmp->next; + } while (true); + } +Also changed the goto in the PCint() loop to be a while/break combination. No change to +code speed, but it looks better and passes the cleanliness "gut check". + +Includes PinChangeIntTest 1.5 sketch. + +...Ooops! Forgot the GetPSTR library, needed for the PinChangeIntTest code! Now it's included. +****************************************************************************** +Version 2.17 (beta) Sat Nov 17 09:46:50 CST 2012 +Another bugfix in the PCINT_MULTI_SERVICE section. I was using sbi(PCIFR, PCICRbit); +I didn't realize that was for I/O ports, and not ATmega registers. +But according to "deprecated.h", +"These macros became obsolete, as reading and writing IO ports can + be done by simply using the IO port name in an expression, and all + bit manipulation (including those on IO ports) can be done using + generic C bit manipulation operators." +So now I do: + PCIFR |= PCICRbit; +****************************************************************************** +Version 2.15 (beta) Sat Nov 17 01:17:44 CST 2012 +Fixed it so that attachInterrupt() will now follow your changes to the user function, +as well as the mode. detachInterrupt() still does not delete the PCintPin object but +at least you can detach and reattach at will, using different modes (RISING, FALLING, +CHANGE) and different functions as you wish. + +****************************************************************************** +Version 2.13 (beta) Mon Nov 12 09:33:06 CST 2012 +SIGNIFICANT BUGFIX release! Significant changes: +1. PCintPort::curr bug. Interrupts that occur rapidly will likely not get serviced properly by PCint(). +2. PCint() interrupt handler optimization. +3. PCIFR port bit set bug fix. +4. Many static variables added for debugging; used only when #define PINMODE is on. +5. detachInterrupt() no longer does a delete(), since that wasn't working anyway. When you detachInterrupt(), the PORT just disables interrupts for that pin; the PCintPin object remains in memory and in the linked list of pins (possibly slowing down your interrupts a couple of micros). You can reenable a detached interrupt- but you must do it within the PinChangeInt library (would anyone ever enable an interrupt on a pin, then disable it, then have need to reenable it but not using the library?). +6. attachInterrupt() now returns a uint8_t value: 1 on successful attach, 0 on successful attach but using an already-enabled pin, and -1 if the new() operator failed to create a PCintPin object. +Also, modified these release notes. + +Details: + +Uncovered a nasty bug, thanks to robtillaart on the Arduino Forums and Andre' Franken who posted to the PinChangeInt groups. This bug was introduced by me when I assigned PCintPort::curr early in the interrupt handler: +ISR(PCINT0_vect) { + PCintPort::curr = portB.portInputReg; + portB.PCint(); +} +Later, in the interrupt handler PCint(), we loop as long as PCIFR indicates a new interrupt wants to be triggered, provided DISABLE_PCINT_MULTI_SERVICE is not defined (it is not by default): +#ifndef DISABLE_PCINT_MULTI_SERVICE + pcifr = PCIFR & PCICRbit; + PCIFR = pcifr; // clear the interrupt if we will process it (no effect if bit is zero) +} while(pcifr); +#endif +...Well. Problem is, if a pin pops up and causes the PCIFR to change, we have to reread the port and look at how it is now! I wasn't doing that before, so if a new interrupt appeared while I was still servicing the old one, odd behavior would take place. For example, an interrupt would register but then the userFunc would not be called upon to service it. The code needs to be: + pcifr = PCIFR & PCICRbit; + PCIFR = pcifr; // clear the interrupt if we will process it (no effect if bit is zero) + PCintPort::curr=portInputReg; // ...Fixed in 2.11beta. +} while(pcifr); + +Also, made the interrupt handler even faster with an optimization from robtillaart to take out the checks for changed pins from the while() loop that steps through the pins: +uint8_t changedPins = (PCintPort::curr ^ lastPinView) & + ((portRisingPins & PCintPort::curr ) | ( portFallingPins & ~PCintPort::curr )); + +...This speedup is offset by more changes in the PCint() handler, which now looks like the following; there are two bug fixes: +---------------------------- +FIX 1: sbi(PCIFR, PCICRbit); +FIX 2: ...the aforementioned PCintPort::curr=portInputReg; +Here's the new code: +---------------------------- + #ifndef DISABLE_PCINT_MULTI_SERVICE + pcifr = PCIFR & PCICRbit; + if (pcifr) { + //if (PCIFR & PCICRbit) { // believe it or not, this adds .6 micros + sbi(PCIFR, PCICRbit); // This was a BUG: PCIFR = pcifr ...And here is the fix. + #ifdef PINMODE + PCintPort::pcint_multi++; + if (PCIFR & PCICRbit) PCintPort::PCIFRbug=1; // PCIFR & PCICRbit should ALWAYS be 0 here! + #endif + PCintPort::curr=portInputReg; // ...Fixed in 2.11beta. + goto loop; // A goto!!! Don't want to look at the portInputReg gratuitously, so the while() will not do. + } + #endif + +Also I added a lot of variables for debugging when PINMODE is defined, for routing out nasty bugs. I may need them in the future... :-( + +Finally, I am not putting newlines in this commentary so I can make it easier to paste online. + +****************************************************************************** +Version 2.11 (beta) Mon Nov 12 09:33:06 CST 2012 +See version 2.13 (beta) above. No change other than tidying up the release notes. +****************************************************************************** + Version 2.01 (beta) Thu Jun 28 12:35:48 CDT 2012 + ...Wow, Version 2! What? Why? + Modified the way that the pin is tested inside the interrupt subroutine (ISR) PCintPort::PCint(), + to make the interrupt quicker and slightly reduce the memory footprint. The interrupt's time is + reduced by 2 microseconds or about 7%. Instead of using the mode variable, two bitmasks are maintained + for each port. One bitmask contains all the pins that are configured to work on RISING signals, the other + on FALLING signals. A pin configured to work on CHANGE signals will appear in both bitmasks of the port. + Then, the test for a change goes like this: + if (thisChangedPin) { + if ((thisChangedPin & portRisingPins & PCintPort::curr ) || + (thisChangedPin & portFallingPins & ~PCintPort::curr )) { + where portRisingPins is the bitmask for the pins configured to interrupt on RISING signals, and + portFallingPins is the bitmask for the pins configured to interrupt on FALLING signals. Each port includes + these two bitmask variables. + + This is a significant change to some core functionality to the library, and it saves an appreciable amount + of time (2 out of 36 or so micros). Hence, the 2.00 designation. + + Tue Jun 26 12:42:20 CDT 2012 + I was officially given permission to use the PCint library: + + Re: PCint library + « Sent to: GreyGnome on: Today at 08:10:33 AM » + « You have forwarded or responded to this message. » + Quote Reply Remove + HI, + Yeah, I wrote the original PCint library. It was a bit of a hack and the new one has better features. + I intended the code to be freely usable. Didn't really think about a license. Feel free to use it in + your code: I hereby grant you permission. + + I'll investigate the MIT license, and see if it is appropriate. + Chris J. Kiick + Robot builder and all around geek. + + Version 1.81 (beta) Tue Jun 19 07:29:08 CDT 2012 + Created the getPCIntVersion function, and its associated GET_PCINT_VERSION preprocessor macro. The version + is a 16-bit int, therefore versions are represented as a 4-digit integer. 1810, then, is the first beta + release of 1.81x series. 1811 would be a bugfix of 1.810. 1820 would be the production release. + + Reversed the order of this list, so the most recent notes come first. + + Made some variables "volatile", because they are changed in the interrupt code. Thanks, Tony Cappellini! + + Added support for the Arduino Mega! Thanks to cserveny...@gmail.com! + NOTE: I don't have a Mega, so I rely on you to give me error (or working) reports! + To sum it up for the Mega: No Port C, no Port D. Instead, you get Port J and Port K. Port B remains. + Port J, however, is practically useless because there is only 1 pin available for interrupts. + Most of the Port J pins are not even connected to a header connector. Caveat Programmer. + + Created a function to report the version of this code. Put this #define ahead of the #include of this file, + in your sketch: + #define GET_PCINT_VERSION + Then you can call + uint16_t getPCIntVersion (); + and it will return a 16-bit integer representation of the version of this library. That is, version 1.73beta + will be reported as "1730". 1.74, then, will return "1740". And so on, for whatever version of the library + this happens to be. The odd number in the 10's position will indicate a beta version, as per usual, and the + number in the 1s place will indicate the beta revision (bugs may necessitate a 1.731, 1.732, etc.). + + Here are some of his notes based on his changes: + Mega and friends are using port B, J and K for interrupts. B is working without any modifications. + + J is mostly useless, because of the hardware UART. I was not able to get pin change notifications from + the TX pin (14), so only 15 left. All other (PORT J) pins are not connected on the Arduino boards. + + K controls Arduino pin A8-A15, working fine. + + 328/168 boards use C and D. So in case the lib is compiled with Mega target, the C and D will be + disabled. Also you cannot see port J/K with other targets. For J and K new flags introduced: + NO_PORTJ_PINCHANGES and NO_PORTK_PINCHANGES. + Maybe we should have PORTJ_PINCHANGES to enable PJ, because they will be most likely unused. + + Enjoy! + + Note: To remain consistent, I have not included PORTJ_PINCHANGES. All ports behave the same, + no matter how trivial those ports may seem... no surprises... + + Version 1.72 Wed Mar 14 18:57:55 CDT 2012 + Release. + + Version 1.71beta Sat Mar 10 12:57:05 CST 2012 + Code reordering: Starting in version 1.3 of this library, I put the code that enables + interrupts for the given pin, and the code that enables Pin Change Interrupts, ahead of actually + setting the user's function for the pin. Thus in the small interval between turning on the + interrupts and actually creating a valid link to an interrupt handler, it is possible to get an + interrupt. At that point the value of the pointer is 0, so this means that the Arduino + will start over again from memory location 0- just as if you'd pressed the reset button. Oops! + + I corrected it so the code now operates in the proper order. + (EDITORIAL NOTE: If you want to really learn something, teach it!) + + Minor code clean-up: All references to PCintPort::curr are now explicit. This changes the compiled + hex code not one whit. I just sleep better at night. + + Numbering: Changed the numbering scheme. Beta versions will end with an odd number in the hundredths + place- because they may be odd- and continue to be marked "beta". I'll just sleep better at night. :-) + + Version 1.70beta Mon Feb 27 07:20:42 CST 2012 + Happy Birthday to me! Happy Birthday tooooo meee! Happy Birthday, Dear Meeeeee-eeeee! + Happy Birthday to me! + + Yes, it is on this auspicious occasion of mine (and Elizabeth Taylor's [R.I.P.]) birthday that I + humbly submit to you, gracious Arduino PinChangeInt user, version 1.70beta of the PinChangeInt + library. I hope you enjoy it. + + New in this release: + The PinChangeIntTest sketch was created, which can be found in the Examples directory. It exercises: + * Two interrupting pins, one on each of the Arduino's PORTs. + * detachInterrupt() (and subsequent attachInterrupt()s). + Hopefully this will help avoid the embarrassing bugs that I have heretofore missed. + + As well, it has come to this author's (GreyGnome) attention that the Serial class in Arduino 1.0 + uses an interrupt that, if you attempt to print from an interrupt (which is what I was doing in my + tests) can easily lock up the Arduino. So I have taken SigurðurOrn's excellent ByteBuffer library + and modified it for my own nefarious purposes. (see http://siggiorn.com/?p=460). The zipfile + comes complete with the ByteBuffer library; see the ByteBuffer/ByteBuffer.h file for a list of + changes, and see the PinChangeIntTest sketch for a usage scenario. Now the (interrupt-less and) + relatively fast operation of filling a circular buffer is used in the interrupt routines. The buffer + is then printed from loop(). + + The library has been modified so it can be used in other libraries, such as my AdaEncoder library + (http://code.google.com/p/adaencoder/). When #include'd by another library you should #define + the LIBCALL_PINCHANGEINT macro. For example: + #ifndef PinChangeInt_h + #define LIBCALL_PINCHANGEINT + #include "../PinChangeInt/PinChangeInt.h" + #endif + This is necessary because the IDE compiles both your sketch and the .cpp file of your library, and + the .h file is included in both places. But since the .h file actually contains the code, any variable + or function definitions would occur twice and cause compilation errors- unless #ifdef'ed out. + + Version 1.6beta Fri Feb 10 08:48:35 CST 2012 + Set the value of the current register settings, first thing in each ISR; e.g., + ISR(PCINT0_vect) { + PCintPort::curr = portB.portInputReg; // version 1.6 + ... + ...instead of at the beginning of the PCintPort::PCint() static method. This means that the port is read + closer to the beginning of the interrupt, and may be slightly more accurate- only by a couple of microseconds, + really, but it's a cheap win. + + Fixed a bug- a BUG!- in the attachInterrupt() and detachInterrupt() methods. I didn't have breaks in my + switch statements! Augh! What am I, a (UNIX) shell programmer? ...Uh, generally, yes... + + Added the PINMODE define and the PCintPort::pinmode variable. + + Version 1.51 Sun Feb 5 23:28:02 CST 2012 + Crap, a bug! Changed line 392 from this: + PCintPort::pinState=curr & changedPins ? HIGH : LOW; + to this: + PCintPort::pinState=curr & p->mask ? HIGH : LOW; + Also added a few lines of (commented-out) debug code. + + Version 1.5 Thu Feb 2 18:09:49 CST 2012 + Added the PCintPort::pinState static variable to allow the programmer to query the state of the pin + at the time of interrupt. + Added two new #defines, NO_PIN_STATE and NO_PIN_NUMBER so as to reduce the code size by 20-50 bytes, + and to speed up the interrupt routine slightly by declaring that you don't care if the static variables + PCintPort::pinState and/or PCintPort::arduinoPin are set and made available to your interrupt routine. + // #define NO_PIN_STATE // to indicate that you don't need the pinState + // #define NO_PIN_NUMBER // to indicate that you don't need the arduinoPin + + Version 1.4 Tue Jan 10 09:41:14 CST 2012 + All the code has been moved into this .h file, so as to allow #define's to work from the user's + sketch. Thanks to Paul Stoffregen from pjrc.com for the inspiration! (Check out his website for + some nice [lots more memory] Arduino-like boards at really good prices. ...This has been an unsolicited + plug. Now back to our regular programming. ...Hehe, "programming", get it?) + + As a result, we no longer use the PinChangeIntConfig.h file. The user must #define things in his/her + sketch. Which is better anyway. + + Removed the pcIntPorts[] array, which created all the ports by default no matter what. Now, only + those ports (PCintPort objects) that you need will get created if you use the NO_PORTx_PINCHANGES #defines. + This saves flash memory, and actually we get a bit of a memory savings anyway even if all the ports are + left enabled. + + The attachInterrupt and detachInterrupt routines were modified to handle the new PCintPort objects. + + Version 1.3 Sat Dec 3 22:56:20 CST 2011 + Significant internal changes: + Tested and modified to work with Arduino 1.0. + + Modified to use the new() operator and symbolic links instead of creating a pre-populated + PCintPins[]. Renamed some variables to simplify or make their meaning more obvious (IMHO anyway). + Modified the PCintPort::PCint() code (ie, the interrupt code) to loop over a linked-list. For + those who love arrays, I have left some code in there that should work to loop over an array + instead. But it is commented out in the release version. + + For Arduino versions prior to 1.0: The new() operator requires the cppfix.h library, which is + included with this package. For Arduino 1.0 and above: new.h comes with the distribution, and + that is #included. + + Version 1.2 Sat Dec 3 Sat Dec 3 09:15:52 CST 2011 + Modified Thu Sep 8 07:33:17 CDT 2011 by GreyGnome. Fixes a bug with the initial port + value. Now it sets the initial value to be the state of the port at the time of + attachInterrupt(). The line is port.PCintLast=port.portInputReg; in attachInterrupt(). + See GreyGnome comment, below. + + Added the "arduinoPin" variable, so the user's function will know exactly which pin on + the Arduino was triggered. + + Version 1.1 Sat Dec 3 00:06:03 CST 2011 + ...updated to fix the "delPin" function as per "pekka"'s bug report. Thanks! + + ---- ^^^ VERSIONS ^^^ (NOTE TO SELF: Update the PCINT_VERSION define, below) ------------- + + See google code project for latest, bugs and info http://code.google.com/p/arduino-pinchangeint/ + For more information Refer to avr-gcc header files, arduino source and atmega datasheet. + + This library was inspired by and derived from "johnboiles" (it seems) + PCInt Arduino Playground example here: http://www.arduino.cc/playground/Main/PcInt + If you are the original author, please let us know at the google code page + + It provides an extension to the interrupt support for arduino by + adding pin change interrupts, giving a way for users to have + interrupts drive off of any pin. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . diff --git a/libraries/PinChangeInt/gpl.txt b/libraries/PinChangeInt/gpl.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/libraries/PinChangeInt/gpl.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/libraries/PinChangeInt/keywords.txt b/libraries/PinChangeInt/keywords.txt new file mode 100644 index 0000000..24e1cec --- /dev/null +++ b/libraries/PinChangeInt/keywords.txt @@ -0,0 +1,10 @@ +# LITERAL1 specifies constants + +# KEYWORD1 specifies datatypes and C/C++ keywords +pinState KEYWORD1 PinState +arduinoPin KEYWORD1 ArduinoPin +PCintPort KEYWORD1 PCInterruptPort + +# KEYWORD2 specifies methods and functions +attachInterrupt KEYWORD2 AttachInterrupt +detachInterrupt KEYWORD2 DetachInterrupt From 5bb8c9b40c6aeace055e25de698370c930e351fb Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 9 Sep 2014 22:33:49 +0200 Subject: [PATCH 010/137] Bugfixes and cleanup --- libraries/MySensors/MyConfig.h | 2 +- libraries/MySensors/MySensor.cpp | 4 +- .../EthernetGateway/EthernetGateway.ino | 22 ++-- .../examples/EthernetGateway/GatewayUtil.h | 3 +- .../examples/MQTTGateway/GatewayUtil.h | 120 ------------------ .../examples/MQTTGateway/MQTTGateway.ino | 6 +- .../MySensors/examples/MQTTGateway/MyMQTT.hx | 83 ------------ .../examples/SerialGateway/SerialGateway.ino | 2 - 8 files changed, 24 insertions(+), 218 deletions(-) delete mode 100644 libraries/MySensors/examples/MQTTGateway/GatewayUtil.h delete mode 100755 libraries/MySensors/examples/MQTTGateway/MyMQTT.hx diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index adcb219..89f7198 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -18,6 +18,6 @@ /*** * Enable/Disable debug logging */ -#define DEBUG +//#define DEBUG #endif diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 5a0670c..2c9b780 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -81,7 +81,9 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b requestNodeId(); } - debug(PSTR("%s started, id %d\n"), repeaterMode?"repeater":"sensor", nc.nodeId); + if (!isGateway) { + debug(PSTR("%s started, id %d\n"), repeaterMode?"repeater":"sensor", nc.nodeId); + } // Open reading pipe for messages directed to this node (set write pipe to same) RF24::openReadingPipe(WRITE_PIPE, TO_ADDR(nc.nodeId)); diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 77f53f8..55c215b 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -104,11 +104,14 @@ void setup() { // Initialize gateway at maximum PA level, channel 70 and callback for write operations gw.begin(incomingMessage, 0, true, 0, RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE); - + // Setup pipes for radio library + gw.openReadingPipe(WRITE_PIPE, BASE_RADIO_ID); + gw.openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); + gw.startListening(); + Ethernet.begin(mac, myIp); setupGateway(RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN, INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output); - // Add led timer interrupt MsTimer2::set(300, ledTimersInterrupt); MsTimer2::start(); @@ -116,12 +119,14 @@ void setup() // Add interrupt for inclusion button to pin PCintPort::attachInterrupt(pinInclusion, startInclusionInterrupt, RISING); - // give the Ethernet interface a second to initialize delay(1000); - + // start listening for clients server.begin(); + + //output(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"), C_INTERNAL, I_GATEWAY_READY); + } @@ -132,20 +137,21 @@ void loop() checkButtonTriggeredInclusion(); checkInclusionFinished(); - + // if an incoming client connects, there will be // bytes available to read via the client object EthernetClient client = server.available(); if (client) { - // if got 1 or more bytes + + // if got 1 or more bytes if (client.available()) { // read the bytes incoming from the client char inChar = client.read(); - if (inputPos #ifdef ARDUINO @@ -48,6 +47,7 @@ void setupGateway(uint8_t _rx, uint8_t _tx, uint8_t _er, uint8_t _inc, uint8_t _ countTx = 0; countErr = 0; + // Setup led pins pinMode(pinRx, OUTPUT); pinMode(pinTx, OUTPUT); @@ -240,7 +240,6 @@ void ledTimersInterrupt() { digitalWrite(pinEr, HIGH); } if(countErr != 255) { countErr--; } - } void rxBlink(uint8_t cnt) { diff --git a/libraries/MySensors/examples/MQTTGateway/GatewayUtil.h b/libraries/MySensors/examples/MQTTGateway/GatewayUtil.h deleted file mode 100644 index 58ff64a..0000000 --- a/libraries/MySensors/examples/MQTTGateway/GatewayUtil.h +++ /dev/null @@ -1,120 +0,0 @@ -#ifndef __GATEWAYUTIL_H__ -#define __GATEWAYUTIL_H__ - -#include - -#ifdef ARDUINO - - -uint8_t pinRx = 8; // Rx led pin -uint8_t pinTx = 9; // Tx led pin -uint8_t pinEr = 7; // Err led pin - -#define MAX_RECEIVE_LENGTH 100 // Max buffersize needed for messages coming from controller -#define MAX_SEND_LENGTH 120 // Max buffersize needed for messages destined for controller - -volatile boolean buttonTriggeredInclusion; -volatile uint8_t countRx; -volatile uint8_t countTx; -volatile uint8_t countErr; - -MyMessage msg; - -void setInclusionMode(boolean newMode); -void txBlink(uint8_t cnt); -void rxBlink(uint8_t cnt); -void errBlink(uint8_t cnt); - -char convBuf[MAX_PAYLOAD*2+1]; -char serialBuffer[MAX_SEND_LENGTH]; // Buffer for building string when sending data to vera -unsigned long inclusionStartTime; - -void setupGateway(uint8_t _rx, uint8_t _tx, uint8_t _er, uint8_t _inc, uint8_t _incTime, void (* _serial)(const char *, ... )) { - inclusionMode = 0; - buttonTriggeredInclusion = false; - serial = _serial; - - pinRx = _rx; - pinTx = _tx; - pinEr = _er; - pinInclusion = _inc; - inclusionTime = _incTime; - - countRx = 0; - countTx = 0; - countErr = 0; - - // Setup led pins - pinMode(pinRx, OUTPUT); - pinMode(pinTx, OUTPUT); - pinMode(pinEr, OUTPUT); - digitalWrite(pinRx, LOW); - digitalWrite(pinTx, LOW); - digitalWrite(pinEr, LOW); - - - // Set initial state of leds - digitalWrite(pinRx, HIGH); - digitalWrite(pinTx, HIGH); - digitalWrite(pinEr, HIGH); - -} - - - -void startInclusionInterrupt() { - buttonTriggeredInclusion = true; -} - - - - - -void ledTimersInterrupt() { - if(countRx && countRx != 255) { - // switch led on - digitalWrite(pinRx, LOW); - } else if(!countRx) { - // switching off - digitalWrite(pinRx, HIGH); - } - if(countRx != 255) { countRx--; } - - if(countTx && countTx != 255) { - // switch led on - digitalWrite(pinTx, LOW); - } else if(!countTx) { - // switching off - digitalWrite(pinTx, HIGH); - } - if(countTx != 255) { countTx--; } - else if(inclusionMode) { countTx = 8; } - - if(countErr && countErr != 255) { - // switch led on - digitalWrite(RADIO_ERROR_LED_PIN, LOW); - } else if(!countErr) { - // switching off - digitalWrite(RADIO_ERROR_LED_PIN, HIGH); - } - if(countErr != 255) { countErr--; } - -} - -void rxBlink(uint8_t cnt) { - if(countRx == 255) { countRx = cnt; } -} -void txBlink(uint8_t cnt) { - if(countTx == 255 && !inclusionMode) { countTx = cnt; } -} -void errBlink(uint8_t cnt) { - if(countErr == 255) { countErr = cnt; } -} - - - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index 388fba8..b7cb4ca 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -144,7 +144,11 @@ void setup() { // Initialize gateway at maximum PA level, channel 70 and callback for write operations gw.begin(incomingMessage, 0, true, 0, RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE); - + // Setup pipes for radio library + gw.openReadingPipe(WRITE_PIPE, BASE_RADIO_ID); + gw.openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); + gw.startListening(); + Ethernet.begin(TCP_MAC, TCP_IP); diff --git a/libraries/MySensors/examples/MQTTGateway/MyMQTT.hx b/libraries/MySensors/examples/MQTTGateway/MyMQTT.hx deleted file mode 100755 index e5d5447..0000000 --- a/libraries/MySensors/examples/MQTTGateway/MyMQTT.hx +++ /dev/null @@ -1,83 +0,0 @@ -/* -The MySensors library adds a new layer on top of the RF24 library. -It handles radio network routing, relaying and ids. - -Created by Henrik Ekblad -Modified by Daniel Wiegert -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -version 2 as published by the Free Software Foundation. -*/ - -#ifndef MyMQTT_h -#define MyMQTT_h - -#include "MySensor.h" - - -////////////////////////////////////////////////////////////////// - -#ifdef DEBUG -#define TCPDUMP // Dump TCP packages. -#endif - -#define MQTT_FIRST_SENSORID 20 // If you want manually configured nodes below this value. 255 = Disable -#define MQTT_LAST_SENSORID 254 // 254 is max! 255 reserved. -#define MQTT_BROKER_PREFIX "MyMQTT" // First prefix in MQTT tree, keep short! -#define MQTT_SEND_SUBSCRIPTION 1 // Send empty payload (request) to node upon MQTT client subscribe request. -// NOTE above : Beware to check if there is any length on payload in your incommingMessage code: -// Example: if (msg.type==V_LIGHT && strlen(msg.getString())>0) otherwise the code might do strange things. - -////////////////////////////////////////////////////////////////// - -#define EEPROM_LATEST_NODE_ADDRESS ((uint8_t)EEPROM_LOCAL_CONFIG_ADDRESS) -#define MQTT_MAX_PACKET_SIZE 100 - -#define MQTTPROTOCOLVERSION 3 -#define MQTTCONNECT 1 // Client request to connect to Server -#define MQTTCONNACK 2 // Connect Acknowledgment -#define MQTTPUBLISH 3 // Publish message -#define MQTTPUBACK 4 // Publish Acknowledgment -#define MQTTPUBREC 5 // Publish Received (assured delivery part 1) -#define MQTTPUBREL 6 // Publish Release (assured delivery part 2) -#define MQTTPUBCOMP 7 // Publish Complete (assured delivery part 3) -#define MQTTSUBSCRIBE 8 // Client Subscribe request -#define MQTTSUBACK 9 // Subscribe Acknowledgment -#define MQTTUNSUBSCRIBE 10 // Client Unsubscribe request -#define MQTTUNSUBACK 11 // Unsubscribe Acknowledgment -#define MQTTPINGREQ 12 // PING Request -#define MQTTPINGRESP 13 // PING Response -#define MQTTDISCONNECT 14 // Client is Disconnecting -#define MQTTReserved 15 // Reserved - -#define MQTTQOS0 (0 << 1) -#define MQTTQOS1 (1 << 1) -#define MQTTQOS2 (2 << 1) - -class MyMQTT : -public MySensor { - -public: - MyMQTT(uint8_t _cepin=5, uint8_t _cspin=6); - void begin(rf24_pa_dbm_e paLevel=RF24_PA_LEVEL_GW, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE, void (*dataCallback) - (const char *, uint8_t *)=NULL, uint8_t _rx=6, uint8_t _tx=5, uint8_t _er=4 ); - void processRadioMessage(); - void processMQTTMessage(char *inputString, uint8_t inputPos); -private: - void (*dataCallback)(const char *, uint8_t *); - void SendMQTT(MyMessage &msg); - void ledTimers(); - void rxBlink(uint8_t cnt); - void txBlink(uint8_t cnt); - void errBlink(uint8_t cnt); - - bool MQTTClientConnected; - char buffer[MQTT_MAX_PACKET_SIZE]; - char convBuf[MAX_PAYLOAD*2+1]; - uint8_t buffsize; - char *getType(char *b, const char **index); -}; - -extern void ledTimersInterrupt(); - -#endif diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index 1d314d6..ed50829 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -63,8 +63,6 @@ void setup() gw.openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); gw.startListening(); - Serial.begin(BAUD_RATE); - setupGateway(RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN, INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output); // Add led timer interrupt From e5bd891a772bd28ad62ba0c1c155363c29490858 Mon Sep 17 00:00:00 2001 From: Yveaux Date: Thu, 11 Sep 2014 09:37:42 +0200 Subject: [PATCH 011/137] Improved parent node search Retry parent node search with each transmit when parent has not been found. Transmit does not block on transmit when no parent has been found as this depletes batteries on battery powered nodes. Fix nRF24 configuration for dynamic ACK's. This bug caused broadcasts to be sent with auto-ACK's. To not break existing functionality parent search can be started when node ID is still unknown. In this case node ID is set to broadcast ID, which can cause funky stuff to happen... --- libraries/MySensors/MySensor.cpp | 141 ++++++++++++++++++------------- libraries/MySensors/MySensor.h | 2 +- 2 files changed, 85 insertions(+), 58 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index e7002d5..907ba43 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -14,9 +14,11 @@ #include "utility/RF24.h" #include "utility/RF24_config.h" +#define DISTANCE_INVALID (0xFF) + // Inline function and macros -inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, uint8_t sensor, uint8_t command, uint8_t type, bool enableAck) { +static inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, uint8_t sensor, uint8_t command, uint8_t type, bool enableAck) { msg.sender = sender; msg.destination = destination; msg.sensor = sensor; @@ -27,6 +29,13 @@ inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, ui return msg; } +static inline bool isValidParent( const uint8_t parent ) { + return parent != AUTO; +} +static inline bool isValidDistance( const uint8_t distance ) { + return distance != DISTANCE_INVALID; +} + MySensor::MySensor(uint8_t _cepin, uint8_t _cspin) : RF24(_cepin, _cspin) { } @@ -37,6 +46,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b isGateway = false; repeaterMode = _repeaterMode; msgCallback = _msgCallback; + failedTransmissions = 0; if (repeaterMode) { setupRepeaterMode(); @@ -52,11 +62,13 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b cc.isMetric = 0x01; } - if (_parentNodeId != AUTO) { + autoFindParent = _parentNodeId == AUTO; + if (!autoFindParent) { nc.parentNodeId = _parentNodeId; - autoFindParent = false; - } else { - autoFindParent = true; + nc.distance = 0; + } else if (!isValidParent(nc.parentNodeId)) { + // Auto find parent, but parent in eeprom is invalid. Force parent search on first transmit. + nc.distance = DISTANCE_INVALID; } if (_nodeId != AUTO) { @@ -64,17 +76,12 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b nc.nodeId = _nodeId; } - // If no parent was found in eeprom. Try to find one. - if (autoFindParent && nc.parentNodeId == 0xff) { - findParentNode(); - } - // Try to fetch node-id from gateway if (nc.nodeId == AUTO) { requestNodeId(); } - debug(PSTR("%s started, id %d\n"), repeaterMode?"repeater":"sensor", nc.nodeId); + debug(PSTR("%s started, id=%d, parent=%d, distance=%d\n"), repeaterMode?"repeater":"sensor", nc.nodeId, nc.parentNodeId, nc.distance); // Open reading pipe for messages directed to this node (set write pipe to same) RF24::openReadingPipe(WRITE_PIPE, TO_ADDR(nc.nodeId)); @@ -93,8 +100,6 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b } void MySensor::setupRadio(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate) { - failedTransmissions = 0; - // Start up the radio library RF24::begin(); @@ -104,13 +109,13 @@ void MySensor::setupRadio(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_ } RF24::setAutoAck(1); RF24::setAutoAck(BROADCAST_PIPE,false); // Turn off auto ack for broadcast - RF24::enableAckPayload(); RF24::setChannel(channel); RF24::setPALevel(paLevel); RF24::setDataRate(dataRate); RF24::setRetries(5,15); RF24::setCRCLength(RF24_CRC_16); RF24::enableDynamicPayloads(); + RF24::enableDynamicAck(); // Required to disable ack-sending for broadcast messages // All nodes listen to broadcast pipe (for FIND_PARENT_RESPONSE messages) RF24::openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); @@ -139,14 +144,12 @@ void MySensor::requestNodeId() { void MySensor::findParentNode() { - failedTransmissions = 0; - - // Set distance to max - nc.distance = 255; - // Send ping message to BROADCAST_ADDRESS (to which all relaying nodes and gateway listens and should reply to) + debug(PSTR("find parent\n")); + build(msg, nc.nodeId, BROADCAST_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT, false).set(""); - sendWrite(BROADCAST_ADDRESS, msg, true); + // Write msg, but suppress recursive parent search + sendWrite(BROADCAST_ADDRESS, msg, false); // Wait for ping response. waitForReply(); @@ -182,44 +185,64 @@ boolean MySensor::sendRoute(MyMessage &message) { } else if (isInternal && message.type == I_ID_RESPONSE && dest==BROADCAST_ADDRESS) { // Node has not yet received any id. We need to send it // by doing a broadcast sending, - return sendWrite(BROADCAST_ADDRESS, message, true); + return sendWrite(BROADCAST_ADDRESS, message); } } if (!isGateway) { - // --- debug(PSTR("route parent\n")); // Should be routed back to gateway. - bool ok = sendWrite(nc.parentNodeId, message); - - if (!ok) { - // Failure when sending to parent node. The parent node might be down and we - // need to find another route to gateway. - if (autoFindParent && failedTransmissions > SEARCH_FAILURES) { - findParentNode(); - } - failedTransmissions++; - } else { - failedTransmissions = 0; - } - return ok; + return sendWrite(nc.parentNodeId, message); } return false; } -boolean MySensor::sendWrite(uint8_t next, MyMessage &message, bool broadcast) { - uint8_t length = mGetLength(message); - message.last = nc.nodeId; - mSetVersion(message, PROTOCOL_VERSION); - // Make sure radio has powered up - RF24::powerUp(); - RF24::stopListening(); - RF24::openWritingPipe(TO_ADDR(next)); - bool ok = RF24::write(&message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length), broadcast); - RF24::startListening(); +boolean MySensor::sendWrite(uint8_t next, MyMessage &message, const bool allowFindParent) { + bool ok = true; + const bool broadcast = next == BROADCAST_ADDRESS; + const bool toParent = next == nc.parentNodeId; + // With current implementation parent node Id can equal the broadcast address when + // starting with empty eeprom and AUTO node Id is active. + // This behavior is undesired, as possible parents will report back to broadcast address. +// debug(PSTR("sendWrite next=%d, parent=%d, distance=%d\n"), next, nc.parentNodeId, nc.distance); + // If sending directly to parent node and distance is not set, then try to find parent now. + if ( allowFindParent && toParent && !isValidDistance(nc.distance) ) { + findParentNode(); + // Known distance indicates parent has been found + ok = isValidDistance(nc.distance); + } - debug(PSTR("send: %d-%d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d,st=%s:%s\n"), - message.sender,message.last, next, message.destination, message.sensor, mGetCommand(message), message.type, mGetPayloadType(message), mGetLength(message), ok?"ok":"fail", message.getString(convBuf)); + if (ok) { + uint8_t length = mGetLength(message); + message.last = nc.nodeId; + mSetVersion(message, PROTOCOL_VERSION); + // Make sure radio has powered up + RF24::powerUp(); + RF24::stopListening(); + RF24::openWritingPipe(TO_ADDR(next)); + // Send message. Disable auto-ack for broadcasts. + ok = RF24::write(&message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length), broadcast); + RF24::startListening(); + debug(PSTR("send: %d-%d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d,st=%s:%s\n"), + message.sender,message.last, next, message.destination, message.sensor, mGetCommand(message), message.type, + mGetPayloadType(message), mGetLength(message), broadcast ? "bc" : (ok ? "ok":"fail"), message.getString(convBuf)); + + // If many successive transmissions to parent failed, the parent node might be down and we + // need to find another route to gateway. + if (toParent) { + if (ok) { + failedTransmissions = 0; + } else { + failedTransmissions++; + if ( autoFindParent && (failedTransmissions >= SEARCH_FAILURES)) { + debug(PSTR("lost parent\n")); + // Set distance invalid to trigger parent search on next write. + nc.distance = DISTANCE_INVALID; + failedTransmissions = 0; + } + } + } + } return ok; } @@ -267,7 +290,6 @@ boolean MySensor::process() { uint8_t len = RF24::getDynamicPayloadSize(); RF24::read(&msg, len); - RF24::writeAckPayload(pipe,&pipe, 1 ); // Add string termination, good if we later would want to print it. msg.data[mGetLength(msg)] = '\0'; @@ -287,10 +309,10 @@ boolean MySensor::process() { if (repeaterMode && command == C_INTERNAL && type == I_FIND_PARENT) { // Relaying nodes should always answer ping messages - // Wait a random delay of 0-2 seconds to minimize collision + // Wait a random delay of 0-1.023 seconds to minimize collision // between ping ack messages from other relaying nodes delay(millis() & 0x3ff); - sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance), true); + sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance)); return false; } else if (destination == nc.nodeId) { // Check if sender requests an ack back. @@ -315,13 +337,18 @@ boolean MySensor::process() { // We've received a reply to a FIND_PARENT message. Check if the distance is // shorter than we already have. uint8_t distance = msg.getByte(); - if (distance Date: Sat, 20 Sep 2014 13:04:01 +0200 Subject: [PATCH 012/137] Made Time, LiquidCrystal and RealTimeClockDisplaySensor example work in Arduino IDE 1.5.7. --- libraries/LiquidCrystal/LCD.cpp | 2 +- libraries/LiquidCrystal/LCD.h | 2 +- libraries/MySensors/MyConfig.h | 2 +- .../EthernetGateway/EthernetGateway.ino | 8 ++-- libraries/Time/DateStrings.cpp | 48 +++++++++---------- 5 files changed, 31 insertions(+), 31 deletions(-) diff --git a/libraries/LiquidCrystal/LCD.cpp b/libraries/LiquidCrystal/LCD.cpp index f0e3068..e7af077 100644 --- a/libraries/LiquidCrystal/LCD.cpp +++ b/libraries/LiquidCrystal/LCD.cpp @@ -304,7 +304,7 @@ void LCD::createChar(uint8_t location, uint8_t charmap[]) } #ifdef __AVR__ -void LCD::createChar(uint8_t location, const prog_uchar charmap[]) +void LCD::createChar(uint8_t location, const unsigned char charmap[]) { location &= 0x7; // we only have 8 memory locations 0-7 diff --git a/libraries/LiquidCrystal/LCD.h b/libraries/LiquidCrystal/LCD.h index 126b935..9b977f4 100644 --- a/libraries/LiquidCrystal/LCD.h +++ b/libraries/LiquidCrystal/LCD.h @@ -418,7 +418,7 @@ public: (0 to 7) @param charmap[in] the bitmap array representing each row of the character. */ - void createChar(uint8_t location, const prog_uchar charmap[]); + void createChar(uint8_t location, const unsigned char charmap[]); #endif // __AVR__ /*! diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 89f7198..adcb219 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -18,6 +18,6 @@ /*** * Enable/Disable debug logging */ -//#define DEBUG +#define DEBUG #endif diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 49a6065..82609c3 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -42,8 +42,8 @@ * 7 Radio error LED (optional) +5V -> LED -> 270-330 Ohm resistor -> pin 7. * 6 Radio SPI Slave Select * 5 Radio Chip Enable - * 3 Inclusion mode button (optional), 10K pull down to GND, button to VCC) - * 2 Radio IRQ pin (optional), W5100 Int, if linked to pin 2) + * 3 Inclusion mode button (optional) GND-> Button -> Pin3 + * 2 Radio IRQ pin (optional) * ----------------------------------------------------------------------------------------------------------- * Powering: both NRF24l01 radio and Ethernet(ENC28J60) uses 3.3V */ @@ -58,10 +58,10 @@ // Use this if you have attached a Ethernet ENC28J60 shields -#include +//#include // Use this fo WizNET module and Arduino Ethernet Shield -//#include +#include #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled diff --git a/libraries/Time/DateStrings.cpp b/libraries/Time/DateStrings.cpp index fc6e15f..a0eef9d 100644 --- a/libraries/Time/DateStrings.cpp +++ b/libraries/Time/DateStrings.cpp @@ -15,38 +15,38 @@ static char buffer[dt_MAX_STRING_LEN+1]; // must be big enough for longest string and the terminating null -char monthStr1[] PROGMEM = "January"; -char monthStr2[] PROGMEM = "February"; -char monthStr3[] PROGMEM = "March"; -char monthStr4[] PROGMEM = "April"; -char monthStr5[] PROGMEM = "May"; -char monthStr6[] PROGMEM = "June"; -char monthStr7[] PROGMEM = "July"; -char monthStr8[] PROGMEM = "August"; -char monthStr9[] PROGMEM = "September"; -char monthStr10[] PROGMEM = "October"; -char monthStr11[] PROGMEM = "November"; -char monthStr12[] PROGMEM = "December"; +const char monthStr1[] PROGMEM = "January"; +const char monthStr2[] PROGMEM = "February"; +const char monthStr3[] PROGMEM = "March"; +const char monthStr4[] PROGMEM = "April"; +const char monthStr5[] PROGMEM = "May"; +const char monthStr6[] PROGMEM = "June"; +const char monthStr7[] PROGMEM = "July"; +const char monthStr8[] PROGMEM = "August"; +const char monthStr9[] PROGMEM = "September"; +const char monthStr10[] PROGMEM = "October"; +const char monthStr11[] PROGMEM = "November"; +const char monthStr12[] PROGMEM = "December"; -PGM_P monthNames_P[] PROGMEM = +PGM_P const monthNames_P[] PROGMEM = { "",monthStr1,monthStr2,monthStr3,monthStr4,monthStr5,monthStr6, monthStr7,monthStr8,monthStr9,monthStr10,monthStr11,monthStr12 }; -char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec"; +const char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec"; -char dayStr0[] PROGMEM = "Err"; -char dayStr1[] PROGMEM = "Sunday"; -char dayStr2[] PROGMEM = "Monday"; -char dayStr3[] PROGMEM = "Tuesday"; -char dayStr4[] PROGMEM = "Wednesday"; -char dayStr5[] PROGMEM = "Thursday"; -char dayStr6[] PROGMEM = "Friday"; -char dayStr7[] PROGMEM = "Saturday"; +const char dayStr0[] PROGMEM = "Err"; +const char dayStr1[] PROGMEM = "Sunday"; +const char dayStr2[] PROGMEM = "Monday"; +const char dayStr3[] PROGMEM = "Tuesday"; +const char dayStr4[] PROGMEM = "Wednesday"; +const char dayStr5[] PROGMEM = "Thursday"; +const char dayStr6[] PROGMEM = "Friday"; +const char dayStr7[] PROGMEM = "Saturday"; -PGM_P dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7}; -char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat"; +PGM_P const dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7}; +const char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat"; /* functions to return date strings */ From 7a304a0523e3feb712ee088232605287ac09cffb Mon Sep 17 00:00:00 2001 From: ToSa27 Date: Sun, 28 Sep 2014 23:43:28 +0200 Subject: [PATCH 013/137] Reduce Bootloader Size changing few uint16 variables to uint8 --- Bootloader/MyOtaBootloader.c | 4 +- Bootloader/MyOtaBootloader.hex | 404 ++++++++++++++++----------------- Bootloader/MyOtaBootloaderHW.h | 5 +- 3 files changed, 205 insertions(+), 208 deletions(-) diff --git a/Bootloader/MyOtaBootloader.c b/Bootloader/MyOtaBootloader.c index cd58712..fe4f24f 100644 --- a/Bootloader/MyOtaBootloader.c +++ b/Bootloader/MyOtaBootloader.c @@ -56,9 +56,9 @@ static uint8_t sendAndWait(uint8_t reqType, uint8_t resType) { msg.type = reqType; for (uint8_t i = 0; i < 10; i++) { sendWrite(msg); - for (uint16_t j = 0; j < 20; j++) { + for (uint8_t j = 0; j < 20; j++) { wdt_reset(); - for (uint16_t j = 0; j < 100; j++) { + for (uint8_t j = 0; j < 100; j++) { wdt_reset(); uint8_t pipe; boolean avail = available(&pipe); diff --git a/Bootloader/MyOtaBootloader.hex b/Bootloader/MyOtaBootloader.hex index 6fd8c58..538354d 100644 --- a/Bootloader/MyOtaBootloader.hex +++ b/Bootloader/MyOtaBootloader.hex @@ -1,4 +1,4 @@ -:1070000011E0A0E0B1E0E0E4FDE702C005900D92E0 +:1070000011E0A0E0B1E0E8EFFCE702C005900D92CE :10701000A030B107D9F711E0A0E0B1E001C01D92A6 :10702000A83DB107E1F711248091610090E08F70D5 :107030009070909301018093000182E090E020E83D @@ -7,208 +7,204 @@ :107060000FBE20936000A8951092CF011092D0011E :107070001092D1011092D2011092D3011092D4013A :107080001092D5011092D60184B18E6284B92498F1 -:1070900085B1857D85B92A9A8AE090E0B3D184E0F4 -:1070A0006FE520D281E06BE31DD285E06CE41AD25B -:1070B00086E0E5D1682F607D676286E013D280E0CC -:1070C000DED1682F6C6080E00DD287E060E70AD2E5 -:1070D0002A9881E090E096D180E5A6D183E7A4D1FB -:1070E0002A9A81E090E08ED18DE1C9D1682F666047 -:1070F0008DE1F8D18CE1C3D1682F6F638CE1F2D1BF -:1071000082EEADD181EEABD104D280E0B8D1682F50 -:107110006E7F80E0E7D182E00FEF1CEF21EE38EACE -:1071200048EA50E060E070E002D2A89582E091E089 -:1071300060E070E043E050E02DEE39E38AD5A89599 -:107140008091020180930E0180930D014FD22FEFA9 -:10715000209313018091110192E0909310012093EC -:107160000401887083608093110120930F0187E0F0 -:1071700068E04AD3882309F42AD310920F01809142 -:1071800002018F3F09F038C081E00FEF1CEF21EEC4 -:1071900038EA48EA50E060E070E0C9D183E064E09A -:1071A00033D3882309F407D38091320182958695E1 -:1071B0008770813019F48091350105C0882329F446 -:1071C00085E391E028D580930201809102018F3FF1 -:1071D00009F4F1D280910201F999FECF1FBA12BCD5 -:1071E00011BC80BD0FB6F894FA9AF99A0FBE80933D -:1071F0000E0180930D01FAD185E091E06BE171E021 -:1072000048E050E02DEE39E324D5909111019871BA -:10721000809110018770806280931001946C90932C -:1072200011018091050190910601909315018093C1 -:1072300014018091070190910801909317018093A8 -:10724000160180E061E0E0D2882309F4C0D22091E9 -:10725000370130913801809107019091080128177A -:107260003907C9F42091390130913A01809109011F -:1072700090910A012817390771F420913B01309150 -:107280003C0180910B0190910C012817390719F4EA -:107290005DD281119CD240913501509136015093BD -:1072A0000601409305012091370130913801309358 -:1072B0000801209307018091390190913A01909340 -:1072C0000A018093090180913B0190913C019093C8 -:1072D0000C0180930B01F4E1EF2EF1E0FF2E809181 -:1072E00010018770806380931001509315014093C3 -:1072F00014013093170120931601C0E0D0E000E99B -:107300001FEFBB24B394E5E0CE2E71E1D72E4DC024 -:10731000F701D583C48382E063E076D2882309F441 -:107320004AD2902F90599F77E92FF0E0E15BFE4F12 -:10733000ABE3B1E080E10D9001928150E1F790372D -:1073400009F030C03FB7F894F999FECF83E0F80117 -:1073500080935700E89507B600FCFDCFA801AFE485 -:10736000B1E02C9111968C91119790E0982F88277D -:10737000820F911D1296FA010C01B0925700E89508 -:1073800011244E5F5F4FF1E0AF3CBF0751F7F801AA -:10739000C0925700E89507B600FCFDCFD092570089 -:1073A000E8953FBF2196005F1F4F809109019091A2 -:1073B0000A01C817D90708F4ABCFA895C7D188230D -:1073C00049F08BE191E065E071E048E050E024EFA6 -:1073D00039E35BD4F0D180E090E0F999FECF92BD23 -:1073E00081BDF89A80B50895F999FECF1FBA92BD74 -:1073F00081BD60BD0FB6F894FA9AF99A0FBE089550 -:107400000000089540E050E00BC020E030E00000B4 -:107410002F5F3F4F61E0243F3607C9F74F5F5F4F53 -:107420004817590790F308950F931F93182F00E002 -:10743000E7DF17FD02C02B9801C02B9AE1DF2D9AE0 -:1074400083B1110F82958170182BDADF2D98D8DF68 -:107450000F5F083069F7812F1F910F9108951F93D7 -:10746000182F2A9881E090E0CDDF812FDDDF182FE3 -:107470002A9A81E090E0C6DF812F1F9108951F9323 -:10748000182F2A9881E090E0BDDF812F8F71CCDF2B -:107490008FEFCADF182F2A9A81E090E0B3DF812FA7 -:1074A0001F9108950F931F93CF93DF93182FEB0134 -:1074B000042F2A9881E090E0A5DF1F71812F806260 -:1074C000B3DF182F03C08991AFDF01500023D9F734 -:1074D0002A9A81E090E096DF812FDF91CF911F9172 -:1074E0000F9108950F931F93182F062F2A9881E06C -:1074F00090E088DF1F71812F806296DF182F802F28 -:1075000093DF2A9A81E090E07DDF812F1F910F9118 -:10751000089580E0B4DF81FD09C080E0B0DF682F0E -:10752000626080E0DFDF85E090E06CDF08957F92AD -:107530008F929F92AF92BF92CF92DF92EF92FF9283 -:107540000F931F93DF93CF93CDB7DEB728970FB676 -:10755000F894DEBF0FBECDBF782E480159016A01F5 -:107560007B01882381F40093CF019092D001209376 -:10757000D101B092D2014093D301D092D401609353 -:10758000D501F092D60189829A82AB82BC82CD82EB -:10759000DE82EF82F88681E0871538F0872D865FDE -:1075A000BE016F5F7F4F45E07DDF82E068DF21E055 -:1075B00030E002C0220F331F7A94E2F7682F622B6B -:1075C00082E090DF28960FB6F894DEBF0FBECDBFE5 -:1075D000CF91DF911F910F91FF90EF90DF90CF90AF -:1075E000BF90AF909F908F907F9008957F928F92E1 -:1075F0009F92AF92BF92CF92DF92EF92FF920F9342 -:107600001F93DF93CF93CDB7DEB728970FB6F894CB -:10761000DEBF0FBECDBF8F3F09F483C0082F10E03F -:1076200020E030E040E050E060E070E089831A83C1 -:107630002B833C834D835E836F83788788243CEF64 -:10764000932E21EEA22E98EAB92E88EAC82EDD24C8 -:10765000EE24FF24080D81E09981091708F080E0ED -:10766000192D91E0AA819A1608F090E0E82FE10F19 -:1076700081E0E11708F080E0982B1E2F2A2D772457 -:107680007394BB81AB1608F07724920F81E09217B8 -:1076900008F080E0782A292F3B2D91E0EC81BE167E -:1076A00008F090E0E72DE30F81E0E31708F080E0B9 -:1076B000982B3E2F4C2D77247394FD81CF1608F024 -:1076C0007724940F81E0941708F080E0782A492FFE -:1076D0005D2D91E08E81D81608F090E0E72DE50F42 -:1076E00081E0E51708F080E0982B5E2F6E2D77245F -:1076F0007394AF81EA1608F07724960F81E096170D -:1077000008F080E0782A692F7F0C772D59016A01F3 -:10771000E92E80E00CDF81E09501A6016E2D772D2A -:1077200006DF28960FB6F894DEBF0FBECDBFCF910F -:10773000DF911F910F91FF90EF90DF90CF90BF905E -:10774000AF909F908F907F90089518954091090178 -:1077500050910A0164E0440F551F6A95E1F7E0E09B -:10776000F0E02FEF3FEF19C084912827822F8295F8 -:107770008227082E869586958025082E8695802559 -:107780008770022E232F869507948795302D282702 -:1077900006948795302528273196E417F50720F3BE -:1077A00040E080910B0190910C012817390709F4F2 -:1077B00041E0842F089528E088E190E00FB6F89426 -:1077C000A895809360000FBE20936000FFCFBEDFBE -:1077D0008823C1F088E10FB6F8948093600010927E -:1077E00060000FBE809100019091010120E80FB66A -:1077F000F89420936100809361000FBEE0E0F0E018 -:1078000009950895D8DF08952F923F924F925F9285 -:107810006F927F928F929F92AF92BF92CF92DF92A0 -:10782000EF92FF920F931F93DF93CF93CDB7DEB705 -:10783000E3970FB6F894DEBF0FBECDBF6BA7809362 -:1078400012016624B9E02B2E312C2C0E3D1E2E0188 -:107850000894411C511CD101EDE0F1E081E201905E -:107860000D928150E1F7109103017C842B852AA7AA -:1078700050DE299881E090E0C5DD81EEF0DD82EEFA -:10788000EEDD80E0FCDD682F6E7F80E02BDE30E0F7 -:1078900040E050E060E070E080E090E01CA73DA791 -:1078A0004EA75FA768AB79AB8AAB9BAB8824ACEFE4 -:1078B0009A2EF1EEAF2EE8EABE2E78EAC72EDD242E -:1078C000EE24FF24012F080D81E0011708F080E06D -:1078D000192D91E0EDA59E1608F090E0E82FE10F3C -:1078E00081E0E11708F080E0982B1E2F2A2DE1E0BF -:1078F000FEA5AF1608F0E0E0920F81E0921708F0C5 -:1079000080E0E82B292F3B2D91E08FA5B81608F0D9 -:1079100090E0E30F81E0E31708F080E0982B3E2F22 -:107920004C2DE1E0F8A9CF1608F0E0E0940F81E0DB -:10793000941708F080E0E82B492F5D2D91E089A98C -:10794000D81608F090E0E50F81E0E51708F080E038 -:10795000982B5E2F6E2D81E0EAA9EE1608F080E0EC -:10796000E92FE60F91E0E61708F090E0892B8F0DE4 -:1079700009831A832B833C834D835E83EF8388873F -:107980008AE0B20145E08EDD80E1B20145E08ADDAA -:10799000FAA5FF3F11F010EA01C010EB769476943F -:1079A000769427E0720E2A9881E090E02BDD812FFB -:1079B0003BDD81017101E70CF11C04C0F8018191EC -:1079C0008F0132DD0E151F05C9F72A9A81E090E07C -:1079D00019DD299A81E090E015DD299881E090E099 -:1079E00011DD8FEF3CDD8073E1F387E060E77ADD46 -:1079F00084FF02C081EE33DD8CDD80E040DD682F46 -:107A0000616080E06FDD87E060E76CDD0091CF01B1 -:107A10001091D0012091D1013091D2014091D30138 -:107A20005091D4016091D5017091D601802F812BA6 -:107A3000822B832B842B852B862B872B61F009834C -:107A40001A832B833C834D835E836F8378878AE020 -:107A5000B20145E027DD82EE02DD81EE00DD299AEC -:107A600081E090E0CFDCAA24BB24A895CC24DD24BF -:107A7000A89587E104DD80FD9CC08FEFF0DCE82E47 -:107A8000E694F7E0EF22EF1609F493C02A9881E01C -:107A900090E0B8DC80E6C8DC8FEFC6DCF82E2A9ACE -:107AA00081E090E0AFDC20E22F1518F482EED7DC05 -:107AB000FF242A9881E090E0A5DC81E6B5DC0EE2A7 -:107AC00011E006C08FEFB0DCF80181938F01FA94CA -:107AD000FF20C1F72A9A81E090E094DC87E060E71C -:107AE00001DD2A9881E090E08DDC8E2D886A9CDC97 -:107AF0008E2D9ADC2A9A81E090E084DC809131011D -:107B00008770823009F058C0909130018091020155 -:107B1000981709F04EC080913201682F70E0CB01B8 -:107B200087709070039709F034C0809133018830DA -:107B300009F02FC040913501242F332727FD3095C0 -:107B40008091040190E001972817390714F5242F3C -:107B50002F5F2093040140912F0140930301F99975 -:107B6000FECF1FBA81E090E092BD81BD40BD0FB64F -:107B7000F894FA9AF99A0FBEF999FECF1FBA42E02B -:107B800050E052BD41BD20BD0FB6F894FA9AF99A63 -:107B90000FBE8091110190E0862797278770907023 -:107BA000892B39F4809133015BA5851711F481E0AD -:107BB00019C081E090E026DC0894C11CD11C64E669 -:107BC000C616D10409F054CF0894A11CB11C74E16D -:107BD000A716B10409F049CF63948AE0681609F04A -:107BE0003ACE80E0E3960FB6F894DEBF0FBECDBF6D -:107BF000CF91DF911F910F91FF90EF90DF90CF9089 -:107C0000BF90AF909F908F907F906F905F904F90BC -:107C10003F902F900895FC0188279927E89421919F -:107C20002032E9F3293010F02E30C8F32B3241F026 -:107C30002D3239F4689404C00E94613E820F911D78 -:107C4000219120532A30C0F31EF4909581959F4FC7 -:107C50000895A0E0B0E0EFE2FEE30C94733E7C01F7 -:107C6000EB018A01690109C0CE012196F60109954F -:107C7000F70181937F010150104001151105A1F713 -:107C8000CDB7DEB7E8E00C948F3EA0E0B0E0EBE4C7 -:107C9000FEE30C94733EEC017B018A01690109C08B -:107CA000CE012196F70161917F01F60109950150FE -:107CB000104001151105A1F7CDB7DEB7E8E00C942F -:107CC0008F3E7AE0979F902D879F802D910D1124F4 -:107CD00008952F923F924F925F926F927F928F9270 -:107CE0009F92AF92BF92CF92DF92EF92FF920F934B -:107CF0001F93CF93DF93CDB7DEB7CA1BDB0B0FB655 -:107D0000F894DEBF0FBECDBF09942A883988488811 -:107D10005F846E847D848C849B84AA84B984C884A7 -:107D2000DF80EE80FD800C811B81AA81B981CE0F9E -:107D3000D11D0FB6F894DEBF0FBECDBFED01089583 +:1070900085B1857D85B92A9A8AE0B1D184E06FE512 +:1070A00015D281E06BE312D285E06CE40FD286E06A +:1070B000DED1682F607D676286E008D280E0D7D19C +:1070C000682F6C6080E002D287E060E7FFD12A98E9 +:1070D00081E095D180E5A2D183E7A0D12A9A81E011 +:1070E0008ED18DE1C4D1682F66608DE1EFD18CE146 +:1070F000BED1682F6F638CE1E9D182EEAAD181EE17 +:10710000A8D1F9D180E0B3D1682F6E7F80E0DED1C5 +:1071100082E00FEF1CEF21EE38EA48EA50E060E031 +:1071200070E0F6D1A89582E091E060E070E043E085 +:1071300050E02AEE39E369D5A89580910201809349 +:107140000E0180930D0143D22FEF20931301809104 +:10715000110192E0909310012093040188708360E4 +:107160008093110120930F0187E068E03ED38823CC +:1071700009F41ED310920F01809102018F3F09F094 +:1071800038C081E00FEF1CEF21EE38EA48EA50E00A +:1071900060E070E0BDD183E064E027D3882309F488 +:1071A000FBD280913201829586958770813019F4E7 +:1071B0008091350105C0882329F485E391E007D546 +:1071C00080930201809102018F3F09F4E5D2809102 +:1071D0000201F999FECF1FBA12BC11BC80BD0FB6D7 +:1071E000F894FA9AF99A0FBE80930E0180930D01DC +:1071F000EED185E091E06BE171E048E050E02AEEED +:1072000039E303D590911101987180911001877035 +:10721000806280931001946C90931101809105011C +:1072200090910601909315018093140180910701BC +:1072300090910801909317018093160180E061E01E +:10724000D4D2882309F4B4D2209137013091380187 +:10725000809107019091080128173907C9F42091FE +:10726000390130913A018091090190910A01281762 +:10727000390771F420913B0130913C0180910B0161 +:1072800090910C012817390719F451D2811190D22D +:10729000409135015091360150930601409305010C +:1072A0002091370130913801309308012093070174 +:1072B0008091390190913A0190930A0180930901DC +:1072C00080913B0190913C0190930C0180930B01C4 +:1072D000F4E1EF2EF1E0FF2E8091100187708063C2 +:1072E00080931001509315014093140130931701BE +:1072F00020931601C0E0D0E000E91FEFBB24B39457 +:10730000E5E0CE2E71E1D72E4DC0F701D583C483C1 +:1073100082E063E06AD2882309F43ED2902F90592C +:107320009F77E92FF0E0E15BFE4FABE3B1E080E156 +:107330000D9001928150E1F7903709F030C03FB7CE +:10734000F894F999FECF83E0F80180935700E8950F +:1073500007B600FCFDCFA801AFE4B1E02C91119677 +:107360008C91119790E0982F8827820F911D12968B +:10737000FA010C01B0925700E89511244E5F5F4F5F +:10738000F1E0AF3CBF0751F7F801C0925700E89514 +:1073900007B600FCFDCFD0925700E8953FBF21967D +:1073A000005F1F4F8091090190910A01C817D9070A +:1073B00008F4ABCFA895BBD1882349F08BE191E0CD +:1073C00065E071E048E050E021EF39E33AD4E4D1E0 +:1073D00080E090E0F999FECF92BD81BDF89A80B52A +:1073E0000895F999FECF1FBA92BD81BD60BD0FB659 +:1073F000F894FA9AF99A0FBE08950000089590E063 +:107400000AC020E030E000002F5F3F4F41E0243F02 +:107410003407C9F79F5F9817A0F308950F931F9340 +:10742000182F00E0EADF17FD02C02B9801C02B9A4D +:10743000E4DF2D9A83B1110F82958170182BDDDF67 +:107440002D98DBDF0F5F083069F7812F1F910F91B7 +:1074500008951F93182F2A9881E0D1DF812FDEDF56 +:10746000182F2A9A81E0CBDF812F1F9108951F9357 +:10747000182F2A9881E0C3DF812F8F71CFDF8FEF24 +:10748000CDDF182F2A9A81E0BADF812F1F9108954E +:107490000F931F93CF93DF93182FEB01042F2A989C +:1074A00081E0ADDF1F71812F8062B8DF182F03C02C +:1074B0008991B4DF01500023D9F72A9A81E09FDF38 +:1074C000812FDF91CF911F910F9108950F931F93FB +:1074D000182F062F2A9881E092DF1F71812F80627A +:1074E0009DDF182F802F9ADF2A9A81E088DF812F75 +:1074F0001F910F91089580E0BADF81FD08C080E000 +:10750000B6DF682F626080E0E1DF85E078DF089514 +:107510007F928F929F92AF92BF92CF92DF92EF9223 +:10752000FF920F931F93DF93CF93CDB7DEB72897CA +:107530000FB6F894DEBF0FBECDBF782E48015901BB +:107540006A017B01882381F40093CF019092D001DE +:107550002093D101B092D2014093D301D092D401B3 +:107560006093D501F092D60189829A82AB82BC8267 +:10757000CD82DE82EF82F88681E0871538F0872D94 +:10758000865FBE016F5F7F4F45E082DF82E06FDF85 +:1075900021E030E002C0220F331F7A94E2F7682F17 +:1075A000622B82E093DF28960FB6F894DEBF0FBE01 +:1075B000CDBFCF91DF911F910F91FF90EF90DF90A2 +:1075C000CF90BF90AF909F908F907F9008957F92C3 +:1075D0008F929F92AF92BF92CF92DF92EF92FF92E3 +:1075E0000F931F93DF93CF93CDB7DEB728970FB6D6 +:1075F000F894DEBF0FBECDBF8F3F09F483C0082FC4 +:1076000010E020E030E040E050E060E070E089838E +:107610001A832B833C834D835E836F837887882412 +:107620003CEF932E21EEA22E98EAB92E88EAC82EBE +:10763000DD24EE24FF24080D81E09981091708F06C +:1076400080E0192D91E0AA819A1608F090E0E82FC9 +:10765000E10F81E0E11708F080E0982B1E2F2A2D22 +:1076600077247394BB81AB1608F07724920F81E0E6 +:10767000921708F080E0782A292F3B2D91E0EC81C9 +:10768000BE1608F090E0E72DE30F81E0E31708F065 +:1076900080E0982B3E2F4C2D77247394FD81CF16DC +:1076A00008F07724940F81E0941708F080E0782A9E +:1076B000492F5D2D91E08E81D81608F090E0E72DDE +:1076C000E50F81E0E51708F080E0982B5E2F6E2D26 +:1076D00077247394AF81EA1608F07724960F81E03F +:1076E000961708F080E0782A692F7F0C772D5901D2 +:1076F0006A01E92E80E00CDF81E09501A6016E2D84 +:10770000772D06DF28960FB6F894DEBF0FBECDBFEB +:10771000CF91DF911F910F91FF90EF90DF90CF906D +:10772000BF90AF909F908F907F9008951895409153 +:10773000090150910A0164E0440F551F6A95E1F771 +:10774000E0E0F0E02FEF3FEF19C084912827822F6F +:1077500082958227082E869586958025082E869507 +:1077600080258770022E232F869507948795302DCC +:10777000282706948795302528273196E417F507A2 +:1077800020F340E080910B0190910C0128173907FC +:1077900009F441E0842F089528E088E190E00FB6D5 +:1077A000F894A895809360000FBE20936000FFCFEF +:1077B000BEDF8823C1F088E10FB6F89480936000A3 +:1077C000109260000FBE809100019091010120E8AD +:1077D0000FB6F89420936100809361000FBEE0E043 +:1077E000F0E009950895D8DF08952F923F924F92C7 +:1077F0005F926F927F928F929F92AF92BF92CF9241 +:10780000DF92EF92FF920F931F93DF93CF93CDB749 +:10781000DEB7E3970FB6F894DEBF0FBECDBF6BA700 +:10782000809312016624B9E02B2E312C2C0E3D1EC4 +:107830002E010894411C511CD101EDE0F1E081E2E0 +:1078400001900D928150E1F7109103017C842B850A +:107850002AA751DE299881E0D2DD81EEFADD82EEA1 +:10786000F8DD80E004DE682F6E7F80E02FDE30E000 +:1078700040E050E060E070E080E090E01CA73DA7B1 +:107880004EA75FA768AB79AB8AAB9BAB8824ACEF04 +:107890009A2EF1EEAF2EE8EABE2E78EAC72EDD244E +:1078A000EE24FF24012F080D81E0011708F080E08D +:1078B000192D91E0EDA59E1608F090E0E82FE10F5C +:1078C00081E0E11708F080E0982B1E2F2A2DE1E0DF +:1078D000FEA5AF1608F0E0E0920F81E0921708F0E5 +:1078E00080E0E82B292F3B2D91E08FA5B81608F0FA +:1078F00090E0E30F81E0E31708F080E0982B3E2F43 +:107900004C2DE1E0F8A9CF1608F0E0E0940F81E0FB +:10791000941708F080E0E82B492F5D2D91E089A9AC +:10792000D81608F090E0E50F81E0E51708F080E058 +:10793000982B5E2F6E2D81E0EAA9EE1608F080E00C +:10794000E92FE60F91E0E61708F090E0892B8F0D04 +:1079500009831A832B833C834D835E83EF8388875F +:107960008AE0B20145E094DD80E1B20145E090DDBE +:10797000FAA5FF3F11F010EA01C010EB769476945F +:10798000769427E0720E2A9881E039DD812F46DD5A +:1079900081017101E70CF11C04C0F80181918F0194 +:1079A0003DDD0E151F05C9F72A9A81E028DD299AC9 +:1079B00081E025DD299881E022DD8FEF4ADD8073AB +:1079C000E1F387E060E782DD84FF02C081EE41DD04 +:1079D00092DD80E04CDD682F616080E077DD87E03C +:1079E00060E774DD0091CF011091D0012091D101A9 +:1079F0003091D2014091D3015091D4016091D501D1 +:107A00007091D601802F812B822B832B842B852B89 +:107A1000862B872B61F009831A832B833C834D834C +:107A20005E836F8378878AE0B20145E031DD82EEC4 +:107A300010DD81EE0EDD299A81E0E1DCCC24A895F1 +:107A4000DD24A89587E113DD80FD96C08FEF01DD71 +:107A5000E82EE694F7E0EF22EF1609F48DC02A989D +:107A600081E0CDDC80E6DADC8FEFD8DCF82E2A9AD4 +:107A700081E0C5DC20E22F1518F482EEEADCFF2459 +:107A80002A9881E0BCDC81E6C9DC0EE211E006C088 +:107A90008FEFC4DCF80181938F01FA94FF20C1F7C6 +:107AA0002A9A81E0ACDC87E060E710DD2A9881E06B +:107AB000A6DC8E2D886AB2DC8E2DB0DC2A9A81E09D +:107AC0009EDC809131018770823009F057C090911F +:107AD000300180910201981709F04EC08091320167 +:107AE000682F70E0CB0187709070039709F034C065 +:107AF00080913301883009F02FC040913501242F47 +:107B0000332727FD30958091040190E001972817D5 +:107B1000390714F5242F2F5F2093040180912F0142 +:107B200080930301F999FECF1FBA41E050E052BDA6 +:107B300041BD80BD0FB6F894FA9AF99A0FBEF99933 +:107B4000FECF1FBA82E090E092BD81BD20BD0FB68E +:107B5000F894FA9AF99A0FBE8091110190E0862765 +:107B6000972787709070892B39F4809133019BA5FA +:107B7000891711F481E012C081E041DCD394E4E67E +:107B8000DE1609F05ECFC394F4E1CF1609F057CFAB +:107B900063942AE0621609F04FCE80E0E3960FB6B8 +:107BA000F894DEBF0FBECDBFCF91DF911F910F9133 +:107BB000FF90EF90DF90CF90BF90AF909F908F900D +:107BC0007F906F905F904F903F902F900895FC01B1 +:107BD00088279927E89421912032E9F3293010F081 +:107BE0002E30C8F32B3241F02D3239F4689404C0A2 +:107BF0000E943D3E820F911D219120532A30C0F3F7 +:107C00001EF4909581959F4F0895A0E0B0E0EBE0C1 +:107C1000FEE30C944F3E7C01EB018A01690109C02F +:107C2000CE012196F6010995F70181937F0101505C +:107C3000104001151105A1F7CDB7DEB7E8E00C94AF +:107C40006B3EA0E0B0E0E7E2FEE30C944F3EEC01B7 +:107C50007B018A01690109C0CE012196F70161917A +:107C60007F01F60109950150104001151105A1F79A +:107C7000CDB7DEB7E8E00C946B3E7AE0979F902D8D +:107C8000879F802D910D112408952F923F924F923E +:107C90005F926F927F928F929F92AF92BF92CF929C +:107CA000DF92EF92FF920F931F93CF93DF93CDB7A5 +:107CB000DEB7CA1BDB0B0FB6F894DEBF0FBECDBF1D +:107CC00009942A88398848885F846E847D848C84EE +:107CD0009B84AA84B984C884DF80EE80FD800C81F7 +:107CE0001B81AA81B981CE0FD11D0FB6F894DEBFDA +:087CF0000FBECDBFED010895A8 :040000030000700089 :00000001FF diff --git a/Bootloader/MyOtaBootloaderHW.h b/Bootloader/MyOtaBootloaderHW.h index 2eec57b..02740a6 100644 --- a/Bootloader/MyOtaBootloaderHW.h +++ b/Bootloader/MyOtaBootloaderHW.h @@ -32,8 +32,9 @@ static void delayu() { asm("nop"); } -static void delaym(uint16_t t) { - uint16_t d, a; +static void delaym(uint8_t t) { + uint8_t d; + uint16_t a; for (d = 0; d < t; d++) for (a = 0; a < DELAY_M; a++) asm("nop"); From c3dbcd1feadc4d5c32ad1a040b3de69f1bfcac47 Mon Sep 17 00:00:00 2001 From: ToSa27 Date: Sun, 28 Sep 2014 23:47:22 +0200 Subject: [PATCH 014/137] Accept Time Broadcasts NodeJsController sending Time broadcasts every few minutes. Sensor accepting not just Time messages addressed to the specific sensor. --- NodeJsController/NodeJsController.js | 3 +++ libraries/MySensors/MySensor.cpp | 10 +++++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/NodeJsController/NodeJsController.js b/NodeJsController/NodeJsController.js index 8bb67da..2c40fb4 100644 --- a/NodeJsController/NodeJsController.js +++ b/NodeJsController/NodeJsController.js @@ -706,5 +706,8 @@ dbc.connect('mongodb://' + dbAddress + ':' + dbPort + '/' + dbName, function(err } else { throw new Error('unknown Gateway type'); } + setInterval(function() { + sendTime(BROADCAST_ADDRESS, NODE_SENSOR_ID, gw); + }, 5*60*1000); }); diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index de02ac0..e71e1e8 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -322,6 +322,11 @@ boolean MySensor::process() { delay(millis() & 0x3ff); sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance)); return false; + } else if (command == C_INTERNAL && type == I_TIME) { + if (timeCallback != NULL) { + // Deliver time to callback + timeCallback(msg.getULong()); + } } else if (destination == nc.nodeId) { // Check if sender requests an ack back. if (mGetRequestAck(msg)) { @@ -397,11 +402,6 @@ boolean MySensor::process() { } sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_CHILDREN,false).set("")); } - } else if (type == I_TIME) { - if (timeCallback != NULL) { - // Deliver time to callback - timeCallback(msg.getULong()); - } } return false; } From 39bab3dfba5b3f167e15e91bf3ce97f3f79ac317 Mon Sep 17 00:00:00 2001 From: ToSa27 Date: Mon, 29 Sep 2014 00:24:57 +0200 Subject: [PATCH 015/137] Split Application and Driver Layer --- libraries/MySensors/MyConfig.h | 16 +++-- libraries/MySensors/MyDriver.cpp | 4 ++ libraries/MySensors/MyDriver.h | 52 ++++++++++++++ libraries/MySensors/MyDriverNRF24.cpp | 68 +++++++++++++++++++ libraries/MySensors/MyDriverNRF24.h | 32 +++++++++ libraries/MySensors/MySensor.cpp | 68 ++++++------------- libraries/MySensors/MySensor.h | 35 +++------- .../EthernetGateway/EthernetGateway.ino | 12 ++-- .../examples/MQTTGateway/MQTTGateway.ino | 9 +-- .../examples/SerialGateway/SerialGateway.ino | 8 +-- 10 files changed, 200 insertions(+), 104 deletions(-) create mode 100644 libraries/MySensors/MyDriver.cpp create mode 100644 libraries/MySensors/MyDriver.h create mode 100644 libraries/MySensors/MyDriverNRF24.cpp create mode 100644 libraries/MySensors/MyDriverNRF24.h diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index adcb219..8991e99 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -4,16 +4,18 @@ /*** * Configure Sensor Network */ +#define COMMDRIVER_NRF24 + +#ifdef COMMDRIVER_NRF24 +#include "MyDriverNRF24.h" +typedef class MyDriverNRF24 MyDriverClass; #define RF24_CHANNEL 76 //RF channel for the sensor net, 0-127 #define RF24_DATARATE RF24_250KBPS //RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps #define RF24_PA_LEVEL RF24_PA_MAX //Sensor PA Level == RF24_PA_MIN=-18dBm, RF24_PA_LOW=-12dBm, RF24_PA_HIGH=-6dBM, and RF24_PA_MAX=0dBm -#define RF24_PA_LEVEL_GW RF24_PA_LOW //Gateway PA Level, defaults to Sensor net PA Level. Tune here if using an amplified nRF2401+ in your gateway. -#define BASE_RADIO_ID ((uint64_t)0xA8A8E1FC00LL) // This is also act as base value for sensor nodeId addresses. Change this (or channel) if you have more than one sensor network. - -// MySensors online examples defaults -#define DEFAULT_CE_PIN 9 -#define DEFAULT_CS_PIN 10 - +#define RF24_BASE_RADIO_ID ((uint64_t)0xA8A8E1FC00LL) // This is also act as base value for sensor nodeId addresses. Change this (or channel) if you have more than one sensor network. +#define RF24_CE_PIN 9 +#define RF24_CS_PIN 10 +#endif /*** * Enable/Disable debug logging diff --git a/libraries/MySensors/MyDriver.cpp b/libraries/MySensors/MyDriver.cpp new file mode 100644 index 0000000..e592552 --- /dev/null +++ b/libraries/MySensors/MyDriver.cpp @@ -0,0 +1,4 @@ +#include "MyDriver.h" + +MyDriver::MyDriver() { +} diff --git a/libraries/MySensors/MyDriver.h b/libraries/MySensors/MyDriver.h new file mode 100644 index 0000000..fe35f5f --- /dev/null +++ b/libraries/MySensors/MyDriver.h @@ -0,0 +1,52 @@ +#ifndef MyDriver_h +#define MyDriver_h + +#include + +#ifdef DEBUG +#define debug(x,...) debugPrint(x, ##__VA_ARGS__) +#else +#define debug(x,...) +#endif + +#define AUTO 0xFF // 0-254. Id 255 is reserved for auto initialization of nodeId. +#define NODE_SENSOR_ID 0xFF // Node child id is always created for when a node + +// This is the nodeId for sensor net gateway receiver sketch (where all sensors should send their data). +#define GATEWAY_ADDRESS ((uint8_t)0) +#define BROADCAST_ADDRESS ((uint8_t)0xFF) + +class MyDriver +{ +public: + // MyDriver constructor + // different parameters would be needed depending on radio module (e.g. pins connected etc.) + // keeping these parameters as #define's in MyConfig to streamline the driver interface + MyDriver(); + // init() + // different parameters would be needed depending on radio module (e.g. channel, power, crc, etc.) + // keeping these parameters as #define's in MyConfig to streamline the driver interface + virtual void init() = 0; + // setAddress(address) + // set the node address and start listening to that address (and the broadcast address) + virtual void setAddress(uint8_t address) = 0; + // getAddress() + // returns the current address from the radio driver + virtual uint8_t getAddress() = 0; + // send(to, data, len) + // reliable transmission of the data with given length (in bytes) to the destination address + // returns true if successfully submitted + virtual bool send(uint8_t to, const void* data, uint8_t len) = 0; + // available(to) + // returns true if a new packet arrived in the rx buffer + // populates "to" parameter with the address the packet was sent to (either own address or broadcast) + virtual bool available(uint8_t *to) = 0; + // receive(data) + // returns length of received packet + // populates "data" parameter with received data + virtual uint8_t receive(void* data) = 0; + // powers down the radio + virtual void powerDown() = 0; +}; + +#endif diff --git a/libraries/MySensors/MyDriverNRF24.cpp b/libraries/MySensors/MyDriverNRF24.cpp new file mode 100644 index 0000000..f59f2d5 --- /dev/null +++ b/libraries/MySensors/MyDriverNRF24.cpp @@ -0,0 +1,68 @@ +#include "MyDriver.h" +#include "MyDriverNRF24.h" + +MyDriverNRF24::MyDriverNRF24() : MyDriver() { + rf24 = new RF24(RF24_CE_PIN, RF24_CS_PIN); +} + +void MyDriverNRF24::init() { + // Start up the radio library + rf24->begin(); + + if (!rf24->isPVariant()) { + debug(PSTR("check wires\n")); + while(1); + } + rf24->setAutoAck(1); + rf24->setAutoAck(BROADCAST_PIPE,false); // Turn off auto ack for broadcast + rf24->enableAckPayload(); + rf24->setChannel(RF24_CHANNEL); + rf24->setPALevel(RF24_PA_LEVEL); + rf24->setDataRate(RF24_DATARATE); + rf24->setRetries(5,15); + rf24->setCRCLength(RF24_CRC_16); + rf24->enableDynamicPayloads(); + + // All nodes listen to broadcast pipe (for FIND_PARENT_RESPONSE messages) + rf24->openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); +} + +void MyDriverNRF24::setAddress(uint8_t address) { + _address = address; + rf24->openReadingPipe(WRITE_PIPE, TO_ADDR(address)); + rf24->openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(address)); + rf24->startListening(); +} + +uint8_t MyDriverNRF24::getAddress() { + return _address; +} + +bool MyDriverNRF24::send(uint8_t to, const void* data, uint8_t len) { + // Make sure radio has powered up + rf24->powerUp(); + rf24->stopListening(); + rf24->openWritingPipe(TO_ADDR(to)); + bool ok = rf24->write(data, len, to == BROADCAST_ADDRESS); + rf24->startListening(); + return ok; +} + +bool MyDriverNRF24::available(uint8_t *to) { + uint8_t pipe = 255; + boolean avail = rf24->available(&pipe); + if (pipe == CURRENT_NODE_PIPE) + *to = _address; + else if (pipe == BROADCAST_PIPE) + *to = BROADCAST_ADDRESS; + return (rf24->available() && pipe < 6); +} + +uint8_t MyDriverNRF24::receive(void* data) { + uint8_t len = rf24->getDynamicPayloadSize(); + rf24->read(data, len); +} + +void MyDriverNRF24::powerDown() { + rf24->powerDown(); +} diff --git a/libraries/MySensors/MyDriverNRF24.h b/libraries/MySensors/MyDriverNRF24.h new file mode 100644 index 0000000..f329ff3 --- /dev/null +++ b/libraries/MySensors/MyDriverNRF24.h @@ -0,0 +1,32 @@ +#ifndef MyCommDriver_h +#define MyCommDriver_h + +#include "MyConfig.h" +#include "MyDriver.h" +#include +#include "utility/RF24.h" +#include "utility/RF24_config.h" + +#define TO_ADDR(x) (RF24_BASE_RADIO_ID + x) + +#define WRITE_PIPE ((uint8_t)0) +#define CURRENT_NODE_PIPE ((uint8_t)1) +#define BROADCAST_PIPE ((uint8_t)2) + +class MyDriverNRF24 : public MyDriver +{ +public: + MyDriverNRF24(); + void init(); + void setAddress(uint8_t address); + uint8_t getAddress(); + bool send(uint8_t to, const void* data, uint8_t len); + bool available(uint8_t *to); + uint8_t receive(void* data); + void powerDown(); +private: + RF24 *rf24; + uint8_t _address; +}; + +#endif \ No newline at end of file diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index e71e1e8..bf8205f 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -10,9 +10,6 @@ */ #include "MySensor.h" -#include "utility/LowPower.h" -#include "utility/RF24.h" -#include "utility/RF24_config.h" #define DISTANCE_INVALID (0xFF) @@ -36,12 +33,12 @@ static inline bool isValidDistance( const uint8_t distance ) { return distance != DISTANCE_INVALID; } - -MySensor::MySensor(uint8_t _cepin, uint8_t _cspin) : RF24(_cepin, _cspin) { -} + MySensor::MySensor() { + driver = (MyDriver*) new MyDriverClass(); + } -void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId, rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate) { +void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId) { Serial.begin(BAUD_RATE); repeaterMode = _repeaterMode; msgCallback = _msgCallback; @@ -52,7 +49,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b if (repeaterMode) { setupRepeaterMode(); } - setupRadio(paLevel, channel, dataRate); + setupRadio(); // Read settings from EEPROM eeprom_read_block((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); @@ -92,8 +89,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b } // Open reading pipe for messages directed to this node (set write pipe to same) - RF24::openReadingPipe(WRITE_PIPE, TO_ADDR(nc.nodeId)); - RF24::openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(nc.nodeId)); + driver->setAddress(nc.nodeId); // Send presentation for this radio node (attach present(NODE_SENSOR_ID, repeaterMode? S_ARDUINO_REPEATER_NODE : S_ARDUINO_NODE); @@ -107,26 +103,9 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b waitForReply(); } -void MySensor::setupRadio(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate) { - // Start up the radio library - RF24::begin(); - - if (!RF24::isPVariant()) { - debug(PSTR("check wires\n")); - while(1); - } - RF24::setAutoAck(1); - RF24::setAutoAck(BROADCAST_PIPE,false); // Turn off auto ack for broadcast - RF24::setChannel(channel); - RF24::setPALevel(paLevel); - RF24::setDataRate(dataRate); - RF24::setRetries(5,15); - RF24::setCRCLength(RF24_CRC_16); - RF24::enableDynamicPayloads(); - RF24::enableDynamicAck(); // Required to disable ack-sending for broadcast messages - - // All nodes listen to broadcast pipe (for FIND_PARENT_RESPONSE messages) - RF24::openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); +void MySensor::setupRadio() { + failedTransmissions = 0; + driver->init(); } void MySensor::setupRepeaterMode(){ @@ -145,7 +124,7 @@ ControllerConfig MySensor::getConfig() { void MySensor::requestNodeId() { debug(PSTR("req node id\n")); - RF24::openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(nc.nodeId)); + driver->setAddress(nc.nodeId); sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_ID_REQUEST, false).set("")); waitForReply(); } @@ -223,13 +202,7 @@ boolean MySensor::sendWrite(uint8_t next, MyMessage &message, const bool allowFi uint8_t length = mGetLength(message); message.last = nc.nodeId; mSetVersion(message, PROTOCOL_VERSION); - // Make sure radio has powered up - RF24::powerUp(); - RF24::stopListening(); - RF24::openWritingPipe(TO_ADDR(next)); - // Send message. Disable auto-ack for broadcasts. - ok = RF24::write(&message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length), broadcast); - RF24::startListening(); + bool ok = driver->send(next, &message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length)); debug(PSTR("send: %d-%d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d,st=%s:%s\n"), message.sender,message.last, next, message.destination, message.sensor, mGetCommand(message), message.type, @@ -290,14 +263,11 @@ void MySensor::requestTime(void (* _timeCallback)(unsigned long)) { boolean MySensor::process() { - uint8_t pipe; - boolean available = RF24::available(&pipe); - - if (!available || pipe>6) + uint8_t to = 0; + if (!driver->available(&to)) return false; - uint8_t len = RF24::getDynamicPayloadSize(); - RF24::read(&msg, len); + uint8_t len = driver->receive((uint8_t *)&msg); // Add string termination, good if we later would want to print it. msg.data[mGetLength(msg)] = '\0'; @@ -380,7 +350,7 @@ boolean MySensor::process() { debug(PSTR("full\n")); while (1); // Wait here. Nothing else we can do... } else { - RF24::openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(nc.nodeId)); + driver->setAddress(nc.nodeId); eeprom_write_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, nc.nodeId); } debug(PSTR("id=%d\n"), nc.nodeId); @@ -412,7 +382,7 @@ boolean MySensor::process() { } // Return true if message was addressed for this node... return true; - } else if (repeaterMode && pipe == CURRENT_NODE_PIPE) { + } else if (repeaterMode && to == nc.nodeId) { // We should try to relay this message to another node uint8_t route = getChildRoute(msg.destination); @@ -511,7 +481,7 @@ void MySensor::internalSleep(unsigned long ms) { void MySensor::sleep(unsigned long ms) { // Let serial prints finish (debug, log etc) Serial.flush(); - RF24::powerDown(); + driver->powerDown(); pinIntTrigger = 0; internalSleep(ms); } @@ -520,7 +490,7 @@ bool MySensor::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { // Let serial prints finish (debug, log etc) bool pinTriggeredWakeup = true; Serial.flush(); - RF24::powerDown(); + driver->powerDown(); attachInterrupt(interrupt, wakeUp, mode); if (ms>0) { pinIntTrigger = 0; @@ -539,7 +509,7 @@ bool MySensor::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { int8_t MySensor::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) { int8_t retVal = 1; Serial.flush(); // Let serial prints finish (debug, log etc) - RF24::powerDown(); + driver->powerDown(); attachInterrupt(interrupt1, wakeUp, mode1); attachInterrupt(interrupt2, wakeUp2, mode2); if (ms>0) { diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 3a4090e..25ff8fa 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -25,8 +25,6 @@ #include #include #include "utility/LowPower.h" -#include "utility/RF24.h" -#include "utility/RF24_config.h" #endif #ifdef DEBUG @@ -37,9 +35,6 @@ #define BAUD_RATE 115200 -#define AUTO 0xFF // 0-254. Id 255 is reserved for auto initialization of nodeId. -#define NODE_SENSOR_ID 0xFF // Node child id is always created for when a node - // EEPROM start address for mysensors library data #define EEPROM_START 0 // EEPROM location of node id @@ -56,15 +51,6 @@ #define EEPROM_FIRMWARE_CRC_ADDRESS (EEPROM_FIRMWARE_BLOCKS_ADDRESS+2) #define EEPROM_LOCAL_CONFIG_ADDRESS (EEPROM_FIRMWARE_CRC_ADDRESS+2) // First free address for sketch static configuration -// This is the nodeId for sensor net gateway receiver sketch (where all sensors should send their data). -#define GATEWAY_ADDRESS ((uint8_t)0) -#define BROADCAST_ADDRESS ((uint8_t)0xFF) -#define TO_ADDR(x) (BASE_RADIO_ID + x) - -#define WRITE_PIPE ((uint8_t)0) -#define CURRENT_NODE_PIPE ((uint8_t)1) -#define BROADCAST_PIPE ((uint8_t)2) - // Search for a new parent node after this many transmission failures #define SEARCH_FAILURES 5 @@ -80,7 +66,7 @@ struct ControllerConfig { }; #ifdef __cplusplus -class MySensor : public RF24 +class MySensor { public: /** @@ -88,10 +74,8 @@ class MySensor : public RF24 * * Creates a new instance of Sensor class. * - * @param _cepin The pin attached to RF24 Chip Enable on the RF module (default 9) - * @param _cspin The pin attached to RF24 Chip Select (default 10) */ - MySensor(uint8_t _cepin=DEFAULT_CE_PIN, uint8_t _cspin=DEFAULT_CS_PIN); + MySensor(); /** * Begin operation of the MySensors library @@ -101,12 +85,9 @@ class MySensor : public RF24 * @param nodeId The unique id (1-254) for this sensor. Default is AUTO(255) which means sensor tries to fetch an id from controller. * @param repeaterMode Activate repeater mode. This node will forward messages to other nodes in the radio network. Make sure to call process() regularly. Default in false * @param parentNodeId Use this to force node to always communicate with a certain parent node. Default is AUTO which means node automatically tries to find a parent. - * @param paLevel Radio PA Level for this sensor. Default RF24_PA_MAX - * @param channel Radio channel. Default is channel 76 - * @param dataRate Radio transmission speed. Default RF24_1MBPS */ - void begin(void (* msgCallback)(const MyMessage &)=NULL, uint8_t nodeId=AUTO, boolean repeaterMode=false, uint8_t parentNodeId=AUTO, rf24_pa_dbm_e paLevel=RF24_PA_LEVEL, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE); + void begin(void (* msgCallback)(const MyMessage &)=NULL, uint8_t nodeId=AUTO, boolean repeaterMode=false, uint8_t parentNodeId=AUTO); /** * Return the nodes nodeId. @@ -141,6 +122,8 @@ class MySensor : public RF24 */ bool send(MyMessage &msg, bool ack=false); + boolean sendRoute(MyMessage &message); + /** * Send this nodes battery level to gateway. * @param level Level between 0-100(%) @@ -234,10 +217,6 @@ class MySensor : public RF24 */ int8_t sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms=0); - - - boolean sendRoute(MyMessage &message); - #ifdef DEBUG void debugPrint(const char *fmt, ... ); int freeRam(); @@ -252,8 +231,10 @@ class MySensor : public RF24 MyMessage msg; // Buffer for incoming messages. MyMessage ack; // Buffer for ack messages. + MyDriver *driver; + void setupRepeaterMode(); - void setupRadio(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate); + void setupRadio(); boolean sendWrite(uint8_t dest, MyMessage &message, const bool allowFindParent = true ); private: diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 82609c3..da25fb7 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -58,10 +58,10 @@ // Use this if you have attached a Ethernet ENC28J60 shields -//#include +#include // Use this fo WizNET module and Arduino Ethernet Shield -#include +//#include #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled @@ -75,7 +75,7 @@ #define RADIO_TX_LED_PIN 9 // the PCB, on board LED -MySensor gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN); +MySensor gw; #define IP_PORT 5003 // The port you want to open @@ -107,11 +107,7 @@ void output(const char *fmt, ... ) { void setup() { // Initialize gateway at maximum PA level, channel 70 and callback for write operations - gw.begin(incomingMessage, 0, true, 0, RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE); - // Setup pipes for radio library - gw.openReadingPipe(WRITE_PIPE, BASE_RADIO_ID); - gw.openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); - gw.startListening(); + gw.begin(incomingMessage, 0, true, 0); Ethernet.begin(mac, myIp); setupGateway(RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN, INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output); diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index b7cb4ca..5526e68 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -89,7 +89,7 @@ uint8_t TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You ////////////////////////////////////////////////////////////////// -MySensor gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN); +MySensor gw; EthernetServer server = EthernetServer(TCP_PORT); MyMessage msg; char convBuf[MAX_PAYLOAD*2+1]; @@ -143,12 +143,7 @@ void incomingMessage(const MyMessage &message) { void setup() { // Initialize gateway at maximum PA level, channel 70 and callback for write operations - gw.begin(incomingMessage, 0, true, 0, RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE); - // Setup pipes for radio library - gw.openReadingPipe(WRITE_PIPE, BASE_RADIO_ID); - gw.openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); - gw.startListening(); - + gw.begin(incomingMessage, 0, true, 0); Ethernet.begin(TCP_MAC, TCP_IP); diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index ed50829..3ff423f 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -38,7 +38,7 @@ #define RADIO_TX_LED_PIN 5 // the PCB, on board LED -MySensor gw(DEFAULT_CE_PIN, DEFAULT_CS_PIN); +MySensor gw; char inputString[MAX_RECEIVE_LENGTH] = ""; // A string to hold incoming commands from serial/ethernet interface int inputPos = 0; @@ -57,11 +57,7 @@ void output(const char *fmt, ... ) { void setup() { - gw.begin(incomingMessage, 0, true, 0, RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE); - // Stetup pipes for radio library - gw.openReadingPipe(WRITE_PIPE, BASE_RADIO_ID); - gw.openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); - gw.startListening(); + gw.begin(incomingMessage, 0, true, 0); setupGateway(RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN, INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output); From 2647345c4def221e19a7de67b5622ea5fa162533 Mon Sep 17 00:00:00 2001 From: ToSa27 Date: Mon, 29 Sep 2014 10:33:16 +0200 Subject: [PATCH 016/137] Adding defines for different board layouts in MyConfig Adjusted all Gateway examples but only one sensor example so far (DallasTemperature). Other sensor examples should get the same three lines added (not mandatory but helps avoiding unnecessary debugging when selecting the wrong setup) --- libraries/MySensors/MyConfig.h | 32 ++++++++++++++++--- .../DallasTemperatureSensor.ino | 4 +++ .../EthernetGateway/EthernetGateway.ino | 3 ++ .../examples/MQTTGateway/MQTTGateway.ino | 3 ++ .../examples/SerialGateway/SerialGateway.ino | 5 ++- 5 files changed, 41 insertions(+), 6 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 8991e99..31937f1 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -4,17 +4,39 @@ /*** * Configure Sensor Network */ -#define COMMDRIVER_NRF24 + +// pick ONE of these - other board layouts can be easily added this way +#define MYSENSORS_SENSOR +//#define MYSENSORS_SERIAL_GATEWAY +//#define MYSENSORS_ETHERNET_MQTT_GATEWAY + +#ifdef MYSENSORS_SENSOR +#define MYSENSORS_RF_NRF24 +#define RF24_CE_PIN 9 +#define RF24_CS_PIN 10 +#define RF24_PA_LEVEL RF24_PA_MAX +#endif -#ifdef COMMDRIVER_NRF24 +#ifdef MYSENSORS_SERIAL_GATEWAY +#define MYSENSORS_RF_NRF24 +#define RF24_CE_PIN 9 +#define RF24_CS_PIN 10 +#define RF24_PA_LEVEL RF24_PA_LOW +#endif + +#ifdef MYSENSORS_ETHERNET_MQTT_GATEWAY +#define MYSENSORS_RF_NRF24 +#define RF24_CE_PIN 5 +#define RF24_CS_PIN 6 +#define RF24_PA_LEVEL RF24_PA_LOW +#endif + +#ifdef MYSENSORS_RF_NRF24 #include "MyDriverNRF24.h" typedef class MyDriverNRF24 MyDriverClass; #define RF24_CHANNEL 76 //RF channel for the sensor net, 0-127 #define RF24_DATARATE RF24_250KBPS //RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps -#define RF24_PA_LEVEL RF24_PA_MAX //Sensor PA Level == RF24_PA_MIN=-18dBm, RF24_PA_LOW=-12dBm, RF24_PA_HIGH=-6dBM, and RF24_PA_MAX=0dBm #define RF24_BASE_RADIO_ID ((uint64_t)0xA8A8E1FC00LL) // This is also act as base value for sensor nodeId addresses. Change this (or channel) if you have more than one sensor network. -#define RF24_CE_PIN 9 -#define RF24_CS_PIN 10 #endif /*** diff --git a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino index 3c6c2c0..a52c49d 100644 --- a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino @@ -4,6 +4,10 @@ #include #include +#ifndef MYSENSORS_SENSOR +#error Please switch to MYSENSORS_SENSOR in MyConfig.h +#endif + #define ONE_WIRE_BUS 3 // Pin where dallase sensor is connected #define MAX_ATTACHED_DS18B20 16 unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index da25fb7..a6ace27 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -56,6 +56,9 @@ #include #include "GatewayUtil.h" +#ifndef MYSENSORS_ETHERNET_MQTT_GATEWAY +#error Please switch to MYSENSORS_ETHERNET_MQTT_GATEWAY in MyConfig.h +#endif // Use this if you have attached a Ethernet ENC28J60 shields #include diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index 5526e68..219b4e2 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -62,6 +62,9 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway #include #include "MyMQTT.h" +#ifndef MYSENSORS_ETHERNET_MQTT_GATEWAY +#error Please switch to MYSENSORS_ETHERNET_MQTT_GATEWAY in MyConfig.h +#endif #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled #define INCLUSION_MODE_PIN 3 // Digital pin used for inclusion mode button diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index 3ff423f..6ee18a4 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -20,7 +20,7 @@ * - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly * - ERR (red) - fast blink on error during transmission error or recieve crc error */ - + #define NO_PORTB_PINCHANGES #include @@ -30,6 +30,9 @@ #include #include "GatewayUtil.h" +#ifndef MYSENSORS_SERIAL_GATEWAY +#error Please switch to MYSENSORS_SERIAL_GATEWAY in MyConfig.h +#endif #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled #define INCLUSION_MODE_PIN 3 // Digital pin used for inclusion mode button From b97372ed015fdd61f54af628950202cf572e9df6 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Fri, 10 Oct 2014 22:34:14 +0200 Subject: [PATCH 017/137] Added .gitignore to filter stino settings files Stino is a plugin for SublimeText to allow SublimeText to act as an Arduino IDE. --- .gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..619eb92 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +stino.settings From f5ef71230882388da82c5f4571923902a9f0d03c Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Fri, 10 Oct 2014 22:24:19 +0200 Subject: [PATCH 018/137] Support for WIZnet W5100 ethernet module SPI_EN The W5100 module has a SPI_EN signal that enables or disables the SPI bus. A bug in the module causes MISO to be continously driven by the module when SPI_EN is pulled high. This is described in this application note: https://www.google.se/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCAQFjAA&url=http%3A%2F%2Fwww.wiznet.co.kr%2FUpLoad_Files%2FReferenceFiles%2FW5100_AN_SPI.pdf&ei=ij84VK7uM6nNygPqvICYDw&usg=AFQjCNGz1qttBEwG1azc1Eza4j69v1rpDQ&sig2=UUUtb4Dr0F35g8ByHMsyig&bvm=bv.77161500,d.bGQ This commit changes the Ethernet gateway sketch to drive SPI_EN high or low, depending on which module is in use (SPI bus is shared between Ethernet and RF modules). The pin attached to SPI_EN is defined by W5100_SPI_EN. This define can be commented out if SPI_EN is not needed (different module) or if the module manages SPI_EN in hardware (some W5100 shields does this). --- .../EthernetGateway/EthernetGateway.ino | 37 +++++++++++++++++-- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index df3b935..e4d8309 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -2,7 +2,7 @@ /* * Copyright (C) 2013 Henrik Ekblad * - * Contribution by a-lurker + * Contribution by a-lurker and Anticimex * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -38,6 +38,7 @@ * 7 Radio error LED (optional) +5V -> LED -> 270-330 Ohm resistor -> pin 7. * 6 Radio SPI Slave Select * 5 Radio Chip Enable + * 4 Ethernet SPI Enable (optional if using a shield/module that manages SPI_EN signal) * 3 Inclusion mode button (optional), 10K pull down to GND, button to VCC) * 2 Radio IRQ pin (optional), W5100 Int, if linked to pin 2) * ----------------------------------------------------------------------------------------------------------- @@ -59,6 +60,7 @@ #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled #define INCLUSION_MODE_PIN 3 // Digital pin used for inclusion mode button +#define W5100_SPI_EN 4 // Ethernet SPI enable #define RADIO_CE_PIN 5 // radio chip enable #define RADIO_SPI_SS_PIN 6 // radio SPI serial select #define RADIO_ERROR_LED_PIN 7 // Error led pin @@ -86,23 +88,46 @@ MyGateway gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN, INCLUSION_MODE_TIME); char inputString[MAX_RECEIVE_LENGTH] = ""; // A string to hold incoming commands from serial/ethernet interface int inputPos = 0; +void w5100_spi_en(boolean enable) +{ +#ifdef W5100_SPI_EN + if (enable) + { + // Pull up pin + pinMode(W5100_SPI_EN, INPUT); + digitalWrite(W5100_SPI_EN, HIGH); + } + else + { + // Ground pin + pinMode(W5100_SPI_EN, OUTPUT); + digitalWrite(W5100_SPI_EN, LOW); + } +#endif +} + void setup() { - // Initialize gateway at maximum PA level, channel 70 and callback for write operations - gw.begin(RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE, writeEthernet); - + w5100_spi_en(true); + Ethernet.begin(mac); Ethernet.begin(mac, myIp); // give the Ethernet interface a second to initialize delay(1000); + // Initialize gateway at generic GW PA level, channel 70 and callback for write operations + w5100_spi_en(false); + gw.begin(RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE, writeEthernet); + // start listening for clients server.begin(); } // This will be called when data should be written to ethernet void writeEthernet(char *writeBuffer) { + w5100_spi_en(true); server.write(writeBuffer); + w5100_spi_en(false); } @@ -110,6 +135,7 @@ void loop() { // if an incoming client connects, there will be // bytes available to read via the client object + w5100_spi_en(true); EthernetClient client = server.available(); if (client) { @@ -128,7 +154,9 @@ void loop() // echo the string to the serial port Serial.print(inputString); + w5100_spi_en(false); gw.parseAndSend(inputString); + w5100_spi_en(true); // clear the string: inputPos = 0; @@ -143,6 +171,7 @@ void loop() } } } + w5100_spi_en(false); gw.processRadioMessage(); } From d5ca838371ebb91c3cf36d48d29a8a4d63dcb012 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 21 Oct 2014 23:44:52 +0200 Subject: [PATCH 019/137] Update UIPEthernet library --- libraries/UIPEthernet/README | 4 +- libraries/UIPEthernet/UIPClient.cpp | 40 +++++++------ libraries/UIPEthernet/UIPClient.h | 3 + libraries/UIPEthernet/UIPEthernet.cpp | 59 ++++++++++++++----- libraries/UIPEthernet/UIPEthernet.h | 2 +- .../UIPEthernet/utility/Enc28J60Network.cpp | 29 ++++++--- libraries/UIPEthernet/utility/uip-conf.h | 5 +- .../UIPEthernet/utility/uipethernet-conf.h | 12 +++- 8 files changed, 106 insertions(+), 48 deletions(-) diff --git a/libraries/UIPEthernet/README b/libraries/UIPEthernet/README index ec51f2d..321b334 100644 --- a/libraries/UIPEthernet/README +++ b/libraries/UIPEthernet/README @@ -1,4 +1,4 @@ -This is UIPEthernet version 1.07 +This is UIPEthernet version 1.09 An plugin-replacement of the stock Arduino Ethernet library for ENC28J60 shields and breakout boards. Full support for persistent (streaming) TCP-connections and UDP (Client and Server each), ARP, ICMP, DHCP and DNS. Just include 'UIPEthernet.h' instead of 'Ethernet.h' and use all your code written for the stock Arduino Ethernet lib! @@ -28,7 +28,7 @@ On a Mac, you will want to create a folder named "libraries" in in the "Document Or you download the zipped version of the library from https://github.com/ntruchsess/arduino_uip/releases, and copy the contained directory UIPEthernet to [path to Arduino distribution]\libraries\UIPEthernet. -If you are running Arduino-IDE 1.5.x use release-version 1.57 or checkout branch 'Arduino_1.5.5' +If you are running Arduino-IDE 1.5.x use release-version 1.59 or checkout branch 'Arduino_1.5.x' Additional information can be found on the Arduino website: http://www.arduino.cc/en/Hacking/Libraries diff --git a/libraries/UIPEthernet/UIPClient.cpp b/libraries/UIPEthernet/UIPClient.cpp index ffbb3e1..d199cfe 100644 --- a/libraries/UIPEthernet/UIPClient.cpp +++ b/libraries/UIPEthernet/UIPClient.cpp @@ -226,6 +226,9 @@ newpacket: goto newpacket; } ready: +#if UIP_CLIENT_TIMER >= 0 + u->timer = millis()+UIP_CLIENT_TIMER; +#endif return size-remain; } return -1; @@ -326,6 +329,7 @@ UIPClient::flush() void uipclient_appcall(void) { + uint16_t send_len = 0; uip_userdata_t *u = (uip_userdata_t*)uip_conn->appstate; if (!u && uip_connected()) { @@ -357,17 +361,16 @@ uipclient_appcall(void) #endif if (uip_len && !(u->state & (UIP_CLIENT_CLOSE | UIP_CLIENT_REMOTECLOSED))) { - memhandle newPacket = Enc28J60Network::allocBlock(uip_len); - if (newPacket != NOBLOCK) + for (uint8_t i=0; i < UIP_SOCKET_NUMPACKETS; i++) { - for (uint8_t i=0; i < UIP_SOCKET_NUMPACKETS; i++) + if (u->packets_in[i] == NOBLOCK) { - if (u->packets_in[i] == NOBLOCK) + u->packets_in[i] = Enc28J60Network::allocBlock(uip_len); + if (u->packets_in[i] != NOBLOCK) { + Enc28J60Network::copyPacket(u->packets_in[i],0,UIPEthernetClass::in_packet,((uint8_t*)uip_appdata)-uip_buf,uip_len); if (i == UIP_SOCKET_NUMPACKETS-1) uip_stop(); - Enc28J60Network::copyPacket(newPacket,0,UIPEthernetClass::in_packet,((uint8_t*)uip_appdata)-uip_buf,uip_len); - u->packets_in[i] = newPacket; goto finish_newdata; } } @@ -404,7 +407,7 @@ finish_newdata: UIPClient::_dumpAllData(); #endif uip_conn->appstate = NULL; - goto nodata; + goto finish; } if (uip_acked()) { @@ -422,26 +425,25 @@ finish_newdata: { if (u->packets_out[1] == NOBLOCK) { - uip_len = u->out_pos; - if (uip_len > 0) + send_len = u->out_pos; + if (send_len > 0) { - Enc28J60Network::resizeBlock(u->packets_out[0],0,uip_len); + Enc28J60Network::resizeBlock(u->packets_out[0],0,send_len); } } else - uip_len = Enc28J60Network::blockSize(u->packets_out[0]); - if (uip_len > 0) + send_len = Enc28J60Network::blockSize(u->packets_out[0]); + if (send_len > 0) { UIPEthernetClass::uip_hdrlen = ((uint8_t*)uip_appdata)-uip_buf; - UIPEthernetClass::uip_packet = Enc28J60Network::allocBlock(UIPEthernetClass::uip_hdrlen+uip_len); + UIPEthernetClass::uip_packet = Enc28J60Network::allocBlock(UIPEthernetClass::uip_hdrlen+send_len); if (UIPEthernetClass::uip_packet != NOBLOCK) { - Enc28J60Network::copyPacket(UIPEthernetClass::uip_packet,UIPEthernetClass::uip_hdrlen,u->packets_out[0],0,uip_len); + Enc28J60Network::copyPacket(UIPEthernetClass::uip_packet,UIPEthernetClass::uip_hdrlen,u->packets_out[0],0,send_len); UIPEthernetClass::packetstate |= UIPETHERNET_SENDPACKET; - uip_send(uip_appdata,uip_len); } - return; } + goto finish; } } // don't close connection unless all outgoing packets are sent @@ -470,9 +472,9 @@ finish_newdata: } } } -nodata: - UIPEthernetClass::uip_packet = NOBLOCK; - uip_len=0; + finish: + uip_send(uip_appdata,send_len); + uip_len = send_len; } uip_userdata_t * diff --git a/libraries/UIPEthernet/UIPClient.h b/libraries/UIPEthernet/UIPClient.h index ac601da..6c0c006 100644 --- a/libraries/UIPEthernet/UIPClient.h +++ b/libraries/UIPEthernet/UIPClient.h @@ -55,6 +55,9 @@ typedef struct { memhandle packets_in[UIP_SOCKET_NUMPACKETS]; memhandle packets_out[UIP_SOCKET_NUMPACKETS]; memaddress out_pos; +#if UIP_CLIENT_TIMER >= 0 + unsigned long timer; +#endif } uip_userdata_t; class UIPClient : public Client { diff --git a/libraries/UIPEthernet/UIPEthernet.cpp b/libraries/UIPEthernet/UIPEthernet.cpp index ea02c97..91ec70a 100644 --- a/libraries/UIPEthernet/UIPEthernet.cpp +++ b/libraries/UIPEthernet/UIPEthernet.cpp @@ -45,7 +45,7 @@ uint8_t UIPEthernetClass::packetstate(0); IPAddress UIPEthernetClass::_dnsServerAddress; DhcpClass* UIPEthernetClass::_dhcp(NULL); -struct uip_timer UIPEthernetClass::periodic_timer; +unsigned long UIPEthernetClass::periodic_timer; // Because uIP isn't encapsulated within a class we have to use global // variables, so we can only have one TCP/IP stack per program. @@ -183,7 +183,7 @@ UIPEthernetClass::tick() Enc28J60Network::readPacket(in_packet,0,(uint8_t*)uip_buf,UIP_BUFSIZE); if (ETH_HDR ->type == HTONS(UIP_ETHTYPE_IP)) { - uip_packet = in_packet; + uip_packet = in_packet; //required for upper_layer_checksum of in_packet! #ifdef UIPETHERNET_DEBUG Serial.print(F("readPacket type IP, uip_len: ")); Serial.println(uip_len); @@ -220,22 +220,50 @@ UIPEthernetClass::tick() } } - if (uip_timer_expired(&periodic_timer)) + unsigned long now = millis(); + +#if UIP_CLIENT_TIMER >= 0 + boolean periodic = (long)( now - periodic_timer ) >= 0; + for (int i = 0; i < UIP_CONNS; i++) { - uip_timer_restart(&periodic_timer); +#else + if ((long)( now - periodic_timer ) >= 0) + { + periodic_timer = now + UIP_PERIODIC_TIMER; + for (int i = 0; i < UIP_CONNS; i++) { - uip_periodic(i); - // If the above function invocation resulted in data that - // should be sent out on the Enc28J60Network, the global variable - // uip_len is set to a value > 0. - if (uip_len > 0) - { - uip_arp_out(); - network_send(); - } +#endif + uip_conn = &uip_conns[i]; +#if UIP_CLIENT_TIMER >= 0 + if (periodic) + { +#endif + uip_process(UIP_TIMER); +#if UIP_CLIENT_TIMER >= 0 } - + else + { + if ((long)( now - ((uip_userdata_t*)uip_conn->appstate)->timer) >= 0) + uip_process(UIP_POLL_REQUEST); + else + continue; + } +#endif + // If the above function invocation resulted in data that + // should be sent out on the Enc28J60Network, the global variable + // uip_len is set to a value > 0. + if (uip_len > 0) + { + uip_arp_out(); + network_send(); + } + } +#if UIP_CLIENT_TIMER >= 0 + if (periodic) + { + periodic_timer = now + UIP_PERIODIC_TIMER; +#endif #if UIP_UDP for (int i = 0; i < UIP_UDP_CONNS; i++) { @@ -263,6 +291,7 @@ boolean UIPEthernetClass::network_send() Serial.println(uip_hdrlen); #endif Enc28J60Network::writePacket(uip_packet,0,uip_buf,uip_hdrlen); + packetstate &= ~ UIPETHERNET_SENDPACKET; goto sendandfree; } uip_packet = Enc28J60Network::allocBlock(uip_len); @@ -286,7 +315,7 @@ sendandfree: } void UIPEthernetClass::init(const uint8_t* mac) { - uip_timer_set(&periodic_timer, CLOCK_SECOND / 4); + periodic_timer = millis() + UIP_PERIODIC_TIMER; Enc28J60Network::init((uint8_t*)mac); uip_seteth_addr(mac); diff --git a/libraries/UIPEthernet/UIPEthernet.h b/libraries/UIPEthernet/UIPEthernet.h index 3bb18d4..c68d578 100644 --- a/libraries/UIPEthernet/UIPEthernet.h +++ b/libraries/UIPEthernet/UIPEthernet.h @@ -90,7 +90,7 @@ private: static IPAddress _dnsServerAddress; static DhcpClass* _dhcp; - static struct uip_timer periodic_timer; + static unsigned long periodic_timer; static void init(const uint8_t* mac); static void configure(IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet); diff --git a/libraries/UIPEthernet/utility/Enc28J60Network.cpp b/libraries/UIPEthernet/utility/Enc28J60Network.cpp index fbef88d..c7c66fb 100644 --- a/libraries/UIPEthernet/utility/Enc28J60Network.cpp +++ b/libraries/UIPEthernet/utility/Enc28J60Network.cpp @@ -155,7 +155,7 @@ Enc28J60Network::receivePacket() // The above does not work. See Rev. B4 Silicon Errata point 6. if (readReg(EPKTCNT) != 0) { - uint16_t readPtr = nextPacketPtr+6; + uint16_t readPtr = nextPacketPtr+6 > RXSTOP_INIT ? nextPacketPtr+6-RXSTOP_INIT+RXSTART_INIT : nextPacketPtr+6; // Set the read pointer to the start of the received packet writeRegPair(ERDPTL, nextPacketPtr); // read the next packet pointer @@ -168,6 +168,20 @@ Enc28J60Network::receivePacket() // read the receive status (see datasheet page 43) rxstat = readOp(ENC28J60_READ_BUF_MEM, 0); //rxstat |= readOp(ENC28J60_READ_BUF_MEM, 0) << 8; +#ifdef ENC28J60DEBUG + Serial.print("receivePacket ["); + Serial.print(readPtr,HEX); + Serial.print("-"); + Serial.print((readPtr+len) % (RXSTOP_INIT+1),HEX); + Serial.print("], next: "); + Serial.print(nextPacketPtr,HEX); + Serial.print(", stat: "); + Serial.print(rxstat,HEX); + Serial.print(", count: "); + Serial.print(readReg(EPKTCNT)); + Serial.print(" -> "); + Serial.println((rxstat & 0x80)!=0 ? "OK" : "failed"); +#endif // decrement the packet counter indicate we are done with this packet writeOp(ENC28J60_BIT_FIELD_SET, ECON2, ECON2_PKTDEC); // check CRC and symbol errors (see datasheet page 44, table 7-3): @@ -215,10 +229,10 @@ Enc28J60Network::sendPacket(memhandle handle) Serial.print("sendPacket("); Serial.print(handle); Serial.print(") ["); - Serial.print(start); + Serial.print(start,HEX); Serial.print("-"); - Serial.print(end); - Serial.println("]:"); + Serial.print(end,HEX); + Serial.print("]: "); for (uint16_t i=start; i<=end; i++) { Serial.print(readByte(i),HEX); @@ -248,8 +262,8 @@ uint16_t Enc28J60Network::setReadPtr(memhandle handle, memaddress position, uint16_t len) { memblock *packet = handle == UIP_RECEIVEBUFFERHANDLE ? &receivePkt : &blocks[handle]; - memaddress start = packet->begin + position; - + memaddress start = handle == UIP_RECEIVEBUFFERHANDLE && packet->begin + position > RXSTOP_INIT ? packet->begin + position-RXSTOP_INIT+RXSTART_INIT : packet->begin + position; + writeRegPair(ERDPTL, start); if (len > packet->size - position) @@ -313,7 +327,8 @@ Enc28J60Network::copyPacket(memhandle dest_pkt, memaddress dest_pos, memhandle s { memblock *dest = &blocks[dest_pkt]; memblock *src = src_pkt == UIP_RECEIVEBUFFERHANDLE ? &receivePkt : &blocks[src_pkt]; - enc28J60_mempool_block_move_callback(dest->begin+dest_pos,src->begin+src_pos,len); + memaddress start = src_pkt == UIP_RECEIVEBUFFERHANDLE && src->begin + src_pos > RXSTOP_INIT ? src->begin + src_pos-RXSTOP_INIT+RXSTART_INIT : src->begin + src_pos; + enc28J60_mempool_block_move_callback(dest->begin+dest_pos,start,len); // Move the RX read pointer to the start of the next received packet // This frees the memory we just read out setERXRDPT(); diff --git a/libraries/UIPEthernet/utility/uip-conf.h b/libraries/UIPEthernet/utility/uip-conf.h index 814aeb9..e7f20d8 100644 --- a/libraries/UIPEthernet/utility/uip-conf.h +++ b/libraries/UIPEthernet/utility/uip-conf.h @@ -87,7 +87,7 @@ typedef unsigned short uip_stats_t; * * \hideinitializer */ -#define UIP_CONF_MAX_LISTENPORTS 4 +#define UIP_CONF_MAX_LISTENPORTS 1 /** * uIP buffer size. @@ -131,12 +131,13 @@ typedef unsigned short uip_stats_t; */ #define UIP_CONF_LOGGING 0 +#define UIP_CONF_UDP 0 /** * UDP support on or off * (see uipethernet-conf.h) * \hideinitializer * - * #define UIP_CONF_UDP 1 + * * #define UIP_CONF_UDP_CONNS 4 */ diff --git a/libraries/UIPEthernet/utility/uipethernet-conf.h b/libraries/UIPEthernet/utility/uipethernet-conf.h index 016e0e3..9dd8b27 100644 --- a/libraries/UIPEthernet/utility/uipethernet-conf.h +++ b/libraries/UIPEthernet/utility/uipethernet-conf.h @@ -5,8 +5,9 @@ #define UIP_SOCKET_NUMPACKETS 5 #define UIP_CONF_MAX_CONNECTIONS 4 -/* for UDP */ -#define UIP_CONF_UDP 0 +/* for UDP + * set UIP_CONF_UDP to 0 to disable UDP (saves aprox. 5kb flash) */ +#define UIP_CONF_UDP 1 #define UIP_CONF_BROADCAST 1 #define UIP_CONF_UDP_CONNS 4 @@ -18,4 +19,11 @@ * if set to a number <= 0 connect will timeout when uIP does (which might be longer than you expect...) */ #define UIP_CONNECT_TIMEOUT -1 +/* periodic timer for uip (in ms) */ +#define UIP_PERIODIC_TIMER 250 + +/* timer to poll client for data after last write (in ms) + * set to -1 to disable fast polling and rely on periodic only (saves 100 bytes flash) */ +#define UIP_CLIENT_TIMER 10 + #endif From 8ec2ebdfce691eba0a293e76aca385d58982af6c Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 23 Oct 2014 09:02:30 +0200 Subject: [PATCH 020/137] Sent startup message to controller when it connects. --- .../examples/EthernetGateway/EthernetGateway.ino | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 6ad2e78..59599ec 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -62,10 +62,10 @@ #endif // Use this if you have attached a Ethernet ENC28J60 shields -#include +//#include // Use this fo WizNET module and Arduino Ethernet Shield -//#include +#include #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled @@ -97,6 +97,7 @@ EthernetServer server = EthernetServer(IP_PORT); char inputString[MAX_RECEIVE_LENGTH] = ""; // A string to hold incoming commands from serial/ethernet interface int inputPos = 0; +bool sentReady = false; void w5100_spi_en(boolean enable) { @@ -151,7 +152,7 @@ void setup() server.begin(); w5100_spi_en(false); - //output(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"), C_INTERNAL, I_GATEWAY_READY); + output(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"), C_INTERNAL, I_GATEWAY_READY); } @@ -170,7 +171,12 @@ void loop() EthernetClient client = server.available(); if (client) { - + if (!sentReady) { + // Send gateway startup message when first client connects + output(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"), C_INTERNAL, I_GATEWAY_READY); + sentReady = true; + } + // if got 1 or more bytes if (client.available()) { // read the bytes incoming from the client From 3d2d7db84517d80ea398c7a6825d87350ef37a5a Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Sat, 25 Oct 2014 10:49:32 +0200 Subject: [PATCH 021/137] Fix problem reported by Yveaux here: https://github.com/mysensors/Arduino/commit/aeb9f30482532122b624fe4f061b5176571b0c6b#commitcomment-8300974 --- libraries/MySensors/MyDriverNRF24.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MyDriverNRF24.cpp b/libraries/MySensors/MyDriverNRF24.cpp index f59f2d5..a6b3ac1 100644 --- a/libraries/MySensors/MyDriverNRF24.cpp +++ b/libraries/MySensors/MyDriverNRF24.cpp @@ -15,13 +15,13 @@ void MyDriverNRF24::init() { } rf24->setAutoAck(1); rf24->setAutoAck(BROADCAST_PIPE,false); // Turn off auto ack for broadcast - rf24->enableAckPayload(); rf24->setChannel(RF24_CHANNEL); rf24->setPALevel(RF24_PA_LEVEL); rf24->setDataRate(RF24_DATARATE); rf24->setRetries(5,15); rf24->setCRCLength(RF24_CRC_16); rf24->enableDynamicPayloads(); + rf24->enableDynamicAck(); // All nodes listen to broadcast pipe (for FIND_PARENT_RESPONSE messages) rf24->openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); From 26138b79721f391bbdadd7669ef2adf4dadef68c Mon Sep 17 00:00:00 2001 From: Frank Olaf Sem-Jacobsen Date: Fri, 31 Oct 2014 20:27:20 +0100 Subject: [PATCH 022/137] RF69 --- libraries/MySensors/MyConfig.h | 8 +++++ libraries/MySensors/MyDriverRF69.cpp | 47 ++++++++++++++++++++++++++++ libraries/MySensors/MyDriverRF69.h | 33 +++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 libraries/MySensors/MyDriverRF69.cpp create mode 100644 libraries/MySensors/MyDriverRF69.h diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index d25a446..4a45ac0 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -12,6 +12,9 @@ // Choose radio type by enabling one of the following #define MYSENSORS_RF_NRF24 +#define MYSENSORS_RF_RF69 + + @@ -20,6 +23,11 @@ typedef class MyDriverNRF24 MyDriverClass; #endif +#ifdef MYSENSORS_RF_RF69 +#include "MyDriverRF69.h" +typedef class MyDriverRF69 MyDriverClass; +#endif + /*** * Enable/Disable debug logging */ diff --git a/libraries/MySensors/MyDriverRF69.cpp b/libraries/MySensors/MyDriverRF69.cpp new file mode 100644 index 0000000..4f733ed --- /dev/null +++ b/libraries/MySensors/MyDriverRF69.cpp @@ -0,0 +1,47 @@ +#include "MyDriver.h" +#include "MyDriverRF69.h" + +MyDriverRF69::MyDriverRF69() : MyDriver() { + driver = new RH_RF69(RF69_CS_PIN, RF69_INTERRUPT_PIN); +} + +void MyDriverRF69::init() { + // Start up the radio library + manager = new RHReliableDatagram(*driver, _address); + driver->setFrequency(RF69_FREQUENCY); + driver->setTxPower(RF69_TRANSMIT_POWER) + +} + +void MyDriverRF69::setAddress(uint8_t address) { + _address = address; + manager->setThisAddress(_address); +} + +uint8_t MyDriverRF69::getAddress() { + return _address; +} + +bool MyDriverRF69::send(uint8_t to, const void* data, uint8_t len) { + // Make sure radio has powered up + uint8_t status = manager->sendtoWait((uint8_t *) data, len, to); + if(status==RH_ROUTER_ERROR_NONE) { + return true; + } else { + return false; + } +} + +bool MyDriverRF69::available(uint8_t *to) { + return manager->available(); +} + +uint8_t MyDriverRF69::receive(void* data) { + uint8_t len = 256; + uint8_t from; + manager->recvfromAck((uint8_t *) data, &len, &from); +} + +void MyDriverRF69::powerDown() { + driver->sleep(); +} diff --git a/libraries/MySensors/MyDriverRF69.h b/libraries/MySensors/MyDriverRF69.h new file mode 100644 index 0000000..635d97f --- /dev/null +++ b/libraries/MySensors/MyDriverRF69.h @@ -0,0 +1,33 @@ +#ifndef MyCommDriver_h +#define MyCommDriver_h + +#include "MyConfig.h" +#include "MyDriver.h" +#include +#include +#include + +#define RF69_FREQUENCY 868; +#define RF69_TRANSMIT_POWER 14; +#define RF69_MODEM_CONFIG RH_RF69::GFSK_Rb250Fd250; +#define RF69_INTERRUPT_PIN 2; +#define RF69_CS_PIN 10; + +class MyDriverRF69 : public MyDriver +{ +public: + MyDriverRF69(); + void init(); + void setAddress(uint8_t address); + uint8_t getAddress(); + bool send(uint8_t to, const void* data, uint8_t len); + bool available(uint8_t *to); + uint8_t receive(void* data); + void powerDown(); +private: + RH_RF69 *driver = NULL; + RHReliableDatagram *manager = NULL; + uint8_t _address; +}; + +#endif \ No newline at end of file From db73e3c7886bbf4254e6787754a2687684b113c0 Mon Sep 17 00:00:00 2001 From: Frank Olaf Sem-Jacobsen Date: Mon, 3 Nov 2014 19:21:40 +0100 Subject: [PATCH 023/137] switched to low-power library --- libraries/MySensors/MyConfig.h | 6 +- libraries/MySensors/MyDriverRF69.cpp | 37 +- libraries/MySensors/MyDriverRF69.h | 29 +- libraries/MySensors/MySensor.cpp | 1 + libraries/MySensors/RFM69.cpp | 464 +++++++++++ libraries/MySensors/RFM69.h | 136 ++++ libraries/MySensors/RFM69registers.h | 1069 ++++++++++++++++++++++++++ 7 files changed, 1713 insertions(+), 29 deletions(-) create mode 100644 libraries/MySensors/RFM69.cpp create mode 100644 libraries/MySensors/RFM69.h create mode 100644 libraries/MySensors/RFM69registers.h diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 4a45ac0..79b1c95 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -6,12 +6,12 @@ */ // pick ONE of these - other board layouts can be easily added this way -#define MYSENSORS_SENSOR -//#define MYSENSORS_SERIAL_GATEWAY +// #define MYSENSORS_SENSOR +#define MYSENSORS_SERIAL_GATEWAY //#define MYSENSORS_ETHERNET_MQTT_GATEWAY // Choose radio type by enabling one of the following -#define MYSENSORS_RF_NRF24 +//#define MYSENSORS_RF_NRF24 #define MYSENSORS_RF_RF69 diff --git a/libraries/MySensors/MyDriverRF69.cpp b/libraries/MySensors/MyDriverRF69.cpp index 4f733ed..126e364 100644 --- a/libraries/MySensors/MyDriverRF69.cpp +++ b/libraries/MySensors/MyDriverRF69.cpp @@ -1,21 +1,24 @@ +#include #include "MyDriver.h" #include "MyDriverRF69.h" MyDriverRF69::MyDriverRF69() : MyDriver() { - driver = new RH_RF69(RF69_CS_PIN, RF69_INTERRUPT_PIN); + radio = new RFM69(); } void MyDriverRF69::init() { // Start up the radio library - manager = new RHReliableDatagram(*driver, _address); - driver->setFrequency(RF69_FREQUENCY); - driver->setTxPower(RF69_TRANSMIT_POWER) + radio->initialize(FREQUENCY,_address,NETWORKID); +#ifdef IS_RFM69HW + radio->setHighPower(); //uncomment only for RFM69HW! +#endif + // radio->encrypt(ENCRYPTKEY); } void MyDriverRF69::setAddress(uint8_t address) { _address = address; - manager->setThisAddress(_address); + radio->setAddress(address); } uint8_t MyDriverRF69::getAddress() { @@ -24,24 +27,24 @@ uint8_t MyDriverRF69::getAddress() { bool MyDriverRF69::send(uint8_t to, const void* data, uint8_t len) { // Make sure radio has powered up - uint8_t status = manager->sendtoWait((uint8_t *) data, len, to); - if(status==RH_ROUTER_ERROR_NONE) { - return true; - } else { - return false; - } + return radio->sendWithRetry(to,data,len); } bool MyDriverRF69::available(uint8_t *to) { - return manager->available(); + return radio->receiveDone(); } uint8_t MyDriverRF69::receive(void* data) { - uint8_t len = 256; - uint8_t from; - manager->recvfromAck((uint8_t *) data, &len, &from); -} + // for (byte i = 0; i < radio->DATALEN; i++){ + // data[i]= (void)radio->DATA[i]; + // } + memcpy(data,(const void *)radio->DATA, radio->DATALEN); + if (radio->ACKRequested()) + { + radio->sendACK(); + } +} void MyDriverRF69::powerDown() { - driver->sleep(); + radio->sleep(); } diff --git a/libraries/MySensors/MyDriverRF69.h b/libraries/MySensors/MyDriverRF69.h index 635d97f..4c53786 100644 --- a/libraries/MySensors/MyDriverRF69.h +++ b/libraries/MySensors/MyDriverRF69.h @@ -4,14 +4,26 @@ #include "MyConfig.h" #include "MyDriver.h" #include -#include -#include +#include "RFM69.h" +#include -#define RF69_FREQUENCY 868; -#define RF69_TRANSMIT_POWER 14; -#define RF69_MODEM_CONFIG RH_RF69::GFSK_Rb250Fd250; -#define RF69_INTERRUPT_PIN 2; -#define RF69_CS_PIN 10; +#define NODEID 2 //unique for each node on same network +#define NETWORKID 100 //the same on all nodes that talk to each other +#define GATEWAYID 1 +//Match frequency to the hardware version of the radio on your Moteino (uncomment one): +// #define FREQUENCY RF69_433MHZ +#define FREQUENCY RF69_868MHZ +//#define FREQUENCY RF69_915MHZ +#define ENCRYPTKEY "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes! +//#define IS_RFM69HW //uncomment only for RFM69HW! Leave out if you have RFM69W! +#define ACK_TIME 30 // max # of ms to wait for an ack +#ifdef __AVR_ATmega1284P__ + #define LED 15 // Moteino MEGAs have LEDs on D15 + #define FLASH_SS 23 // and FLASH SS on D23 +#else + #define LED 9 // Moteinos have LEDs on D9 + #define FLASH_SS 8 // and FLASH SS on D8 +#endif class MyDriverRF69 : public MyDriver { @@ -25,8 +37,7 @@ public: uint8_t receive(void* data); void powerDown(); private: - RH_RF69 *driver = NULL; - RHReliableDatagram *manager = NULL; + RFM69 *radio = NULL; uint8_t _address; }; diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index bf8205f..c56da76 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -275,6 +275,7 @@ boolean MySensor::process() { msg.sender, msg.last, msg.destination, msg.sensor, mGetCommand(msg), msg.type, mGetPayloadType(msg), mGetLength(msg), msg.getString(convBuf)); if(!(mGetVersion(msg) == PROTOCOL_VERSION)) { + debug(PSTR("version: %d\n"),mGetVersion(msg)); debug(PSTR("version mismatch\n")); return false; } diff --git a/libraries/MySensors/RFM69.cpp b/libraries/MySensors/RFM69.cpp new file mode 100644 index 0000000..8b0305f --- /dev/null +++ b/libraries/MySensors/RFM69.cpp @@ -0,0 +1,464 @@ +// ********************************************************************************** +// Driver definition for HopeRF RFM69W/RFM69HW/RFM69CW/RFM69HCW, Semtech SX1231/1231H +// ********************************************************************************** +// Copyright Felix Rusu (2014), felix@lowpowerlab.com +// http://lowpowerlab.com/ +// ********************************************************************************** +// License +// ********************************************************************************** +// This program is free software; you can redistribute it +// and/or modify it under the terms of the GNU General +// Public License as published by the Free Software +// Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will +// be useful, but WITHOUT ANY WARRANTY; without even the +// implied warranty of MERCHANTABILITY or FITNESS FOR A +// PARTICULAR PURPOSE. See the GNU General Public +// License for more details. +// +// You should have received a copy of the GNU General +// Public License along with this program; if not, write +// to the Free Software Foundation, Inc., +// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// Licence can be viewed at +// http://www.fsf.org/licenses/gpl.txt +// +// Please maintain this license information along with authorship +// and copyright notices in any redistribution of this code +// ********************************************************************************** +#include +#include +#include + +volatile byte RFM69::DATA[RF69_MAX_DATA_LEN]; +volatile byte RFM69::_mode; // current transceiver state +volatile byte RFM69::DATALEN; +volatile byte RFM69::SENDERID; +volatile byte RFM69::TARGETID; //should match _address +volatile byte RFM69::PAYLOADLEN; +volatile byte RFM69::ACK_REQUESTED; +volatile byte RFM69::ACK_RECEIVED; /// Should be polled immediately after sending a packet with ACK request +volatile int RFM69::RSSI; //most accurate RSSI during reception (closest to the reception) +RFM69* RFM69::selfPointer; + +bool RFM69::initialize(byte freqBand, byte nodeID, byte networkID) +{ + const byte CONFIG[][2] = + { + /* 0x01 */ { REG_OPMODE, RF_OPMODE_SEQUENCER_ON | RF_OPMODE_LISTEN_OFF | RF_OPMODE_STANDBY }, + /* 0x02 */ { REG_DATAMODUL, RF_DATAMODUL_DATAMODE_PACKET | RF_DATAMODUL_MODULATIONTYPE_FSK | RF_DATAMODUL_MODULATIONSHAPING_00 }, //no shaping + /* 0x03 */ { REG_BITRATEMSB, RF_BITRATEMSB_55555}, //default:4.8 KBPS + /* 0x04 */ { REG_BITRATELSB, RF_BITRATELSB_55555}, + /* 0x05 */ { REG_FDEVMSB, RF_FDEVMSB_50000}, //default:5khz, (FDEV + BitRate/2 <= 500Khz) + /* 0x06 */ { REG_FDEVLSB, RF_FDEVLSB_50000}, + + /* 0x07 */ { REG_FRFMSB, (freqBand==RF69_315MHZ ? RF_FRFMSB_315 : (freqBand==RF69_433MHZ ? RF_FRFMSB_433 : (freqBand==RF69_868MHZ ? RF_FRFMSB_868 : RF_FRFMSB_915))) }, + /* 0x08 */ { REG_FRFMID, (freqBand==RF69_315MHZ ? RF_FRFMID_315 : (freqBand==RF69_433MHZ ? RF_FRFMID_433 : (freqBand==RF69_868MHZ ? RF_FRFMID_868 : RF_FRFMID_915))) }, + /* 0x09 */ { REG_FRFLSB, (freqBand==RF69_315MHZ ? RF_FRFLSB_315 : (freqBand==RF69_433MHZ ? RF_FRFLSB_433 : (freqBand==RF69_868MHZ ? RF_FRFLSB_868 : RF_FRFLSB_915))) }, + + // looks like PA1 and PA2 are not implemented on RFM69W, hence the max output power is 13dBm + // +17dBm and +20dBm are possible on RFM69HW + // +13dBm formula: Pout=-18+OutputPower (with PA0 or PA1**) + // +17dBm formula: Pout=-14+OutputPower (with PA1 and PA2)** + // +20dBm formula: Pout=-11+OutputPower (with PA1 and PA2)** and high power PA settings (section 3.3.7 in datasheet) + ///* 0x11 */ { REG_PALEVEL, RF_PALEVEL_PA0_ON | RF_PALEVEL_PA1_OFF | RF_PALEVEL_PA2_OFF | RF_PALEVEL_OUTPUTPOWER_11111}, + ///* 0x13 */ { REG_OCP, RF_OCP_ON | RF_OCP_TRIM_95 }, //over current protection (default is 95mA) + + // RXBW defaults are { REG_RXBW, RF_RXBW_DCCFREQ_010 | RF_RXBW_MANT_24 | RF_RXBW_EXP_5} (RxBw: 10.4khz) + /* 0x19 */ { REG_RXBW, RF_RXBW_DCCFREQ_010 | RF_RXBW_MANT_16 | RF_RXBW_EXP_2 }, //(BitRate < 2 * RxBw) + //for BR-19200: //* 0x19 */ { REG_RXBW, RF_RXBW_DCCFREQ_010 | RF_RXBW_MANT_24 | RF_RXBW_EXP_3 }, + /* 0x25 */ { REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_01 }, //DIO0 is the only IRQ we're using + /* 0x29 */ { REG_RSSITHRESH, 220 }, //must be set to dBm = (-Sensitivity / 2) - default is 0xE4=228 so -114dBm + ///* 0x2d */ { REG_PREAMBLELSB, RF_PREAMBLESIZE_LSB_VALUE } // default 3 preamble bytes 0xAAAAAA + /* 0x2e */ { REG_SYNCCONFIG, RF_SYNC_ON | RF_SYNC_FIFOFILL_AUTO | RF_SYNC_SIZE_2 | RF_SYNC_TOL_0 }, + /* 0x2f */ { REG_SYNCVALUE1, 0x2D }, //attempt to make this compatible with sync1 byte of RFM12B lib + /* 0x30 */ { REG_SYNCVALUE2, networkID }, //NETWORK ID + /* 0x37 */ { REG_PACKETCONFIG1, RF_PACKET1_FORMAT_VARIABLE | RF_PACKET1_DCFREE_OFF | RF_PACKET1_CRC_ON | RF_PACKET1_CRCAUTOCLEAR_ON | RF_PACKET1_ADRSFILTERING_OFF }, + /* 0x38 */ { REG_PAYLOADLENGTH, 66 }, //in variable length mode: the max frame size, not used in TX + //* 0x39 */ { REG_NODEADRS, nodeID }, //turned off because we're not using address filtering + /* 0x3C */ { REG_FIFOTHRESH, RF_FIFOTHRESH_TXSTART_FIFONOTEMPTY | RF_FIFOTHRESH_VALUE }, //TX on FIFO not empty + /* 0x3d */ { REG_PACKETCONFIG2, RF_PACKET2_RXRESTARTDELAY_2BITS | RF_PACKET2_AUTORXRESTART_ON | RF_PACKET2_AES_OFF }, //RXRESTARTDELAY must match transmitter PA ramp-down time (bitrate dependent) + //for BR-19200: //* 0x3d */ { REG_PACKETCONFIG2, RF_PACKET2_RXRESTARTDELAY_NONE | RF_PACKET2_AUTORXRESTART_ON | RF_PACKET2_AES_OFF }, //RXRESTARTDELAY must match transmitter PA ramp-down time (bitrate dependent) + //* 0x6F */ { REG_TESTDAGC, RF_DAGC_CONTINUOUS }, // run DAGC continuously in RX mode + /* 0x6F */ { REG_TESTDAGC, RF_DAGC_IMPROVED_LOWBETA0 }, // run DAGC continuously in RX mode, recommended default for AfcLowBetaOn=0 + {255, 0} + }; + + pinMode(_slaveSelectPin, OUTPUT); + SPI.begin(); + + do writeReg(REG_SYNCVALUE1, 0xaa); while (readReg(REG_SYNCVALUE1) != 0xaa); + do writeReg(REG_SYNCVALUE1, 0x55); while (readReg(REG_SYNCVALUE1) != 0x55); + + for (byte i = 0; CONFIG[i][0] != 255; i++) + writeReg(CONFIG[i][0], CONFIG[i][1]); + + // Encryption is persistent between resets and can trip you up during debugging. + // Disable it during initialization so we always start from a known state. + encrypt(0); + + setHighPower(_isRFM69HW); //called regardless if it's a RFM69W or RFM69HW + setMode(RF69_MODE_STANDBY); + while ((readReg(REG_IRQFLAGS1) & RF_IRQFLAGS1_MODEREADY) == 0x00); // Wait for ModeReady + attachInterrupt(_interruptNum, RFM69::isr0, RISING); + + selfPointer = this; + _address = nodeID; + return true; +} + +void RFM69::setFrequency(uint32_t FRF) +{ + writeReg(REG_FRFMSB, FRF >> 16); + writeReg(REG_FRFMID, FRF >> 8); + writeReg(REG_FRFLSB, FRF); +} + +void RFM69::setMode(byte newMode) +{ + if (newMode == _mode) return; //TODO: can remove this? + + switch (newMode) { + case RF69_MODE_TX: + writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_TRANSMITTER); + if (_isRFM69HW) setHighPowerRegs(true); + break; + case RF69_MODE_RX: + writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_RECEIVER); + if (_isRFM69HW) setHighPowerRegs(false); + break; + case RF69_MODE_SYNTH: + writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_SYNTHESIZER); + break; + case RF69_MODE_STANDBY: + writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_STANDBY); + break; + case RF69_MODE_SLEEP: + writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_SLEEP); + break; + default: return; + } + + // we are using packet mode, so this check is not really needed + // but waiting for mode ready is necessary when going from sleep because the FIFO may not be immediately available from previous mode + while (_mode == RF69_MODE_SLEEP && (readReg(REG_IRQFLAGS1) & RF_IRQFLAGS1_MODEREADY) == 0x00); // Wait for ModeReady + + _mode = newMode; +} + +void RFM69::sleep() { + setMode(RF69_MODE_SLEEP); +} + +void RFM69::setAddress(byte addr) +{ + _address = addr; + writeReg(REG_NODEADRS, _address); +} + +// set output power: 0=min, 31=max +// this results in a "weaker" transmitted signal, and directly results in a lower RSSI at the receiver +void RFM69::setPowerLevel(byte powerLevel) +{ + _powerLevel = powerLevel; + writeReg(REG_PALEVEL, (readReg(REG_PALEVEL) & 0xE0) | (_powerLevel > 31 ? 31 : _powerLevel)); +} + +bool RFM69::canSend() +{ + if (_mode == RF69_MODE_RX && PAYLOADLEN == 0 && readRSSI() < CSMA_LIMIT) //if signal stronger than -100dBm is detected assume channel activity + { + setMode(RF69_MODE_STANDBY); + return true; + } + return false; +} + +void RFM69::send(byte toAddress, const void* buffer, byte bufferSize, bool requestACK) +{ + writeReg(REG_PACKETCONFIG2, (readReg(REG_PACKETCONFIG2) & 0xFB) | RF_PACKET2_RXRESTART); // avoid RX deadlocks + long now = millis(); + while (!canSend() && millis()-now < RF69_CSMA_LIMIT_MS) receiveDone(); + sendFrame(toAddress, buffer, bufferSize, requestACK, false); +} + +// to increase the chance of getting a packet across, call this function instead of send +// and it handles all the ACK requesting/retrying for you :) +// The only twist is that you have to manually listen to ACK requests on the other side and send back the ACKs +// The reason for the semi-automaton is that the lib is ingterrupt driven and +// requires user action to read the received data and decide what to do with it +// replies usually take only 5-8ms at 50kbps@915Mhz +bool RFM69::sendWithRetry(byte toAddress, const void* buffer, byte bufferSize, byte retries, byte retryWaitTime) { + long sentTime; + for (byte i=0; i<=retries; i++) + { + send(toAddress, buffer, bufferSize, true); + sentTime = millis(); + while (millis()-sentTime RF69_MAX_DATA_LEN) bufferSize = RF69_MAX_DATA_LEN; + + //write to FIFO + select(); + SPI.transfer(REG_FIFO | 0x80); + SPI.transfer(bufferSize + 3); + SPI.transfer(toAddress); + SPI.transfer(_address); + + //control byte + if (sendACK) + SPI.transfer(0x80); + else if (requestACK) + SPI.transfer(0x40); + else SPI.transfer(0x00); + + for (byte i = 0; i < bufferSize; i++) + SPI.transfer(((byte*)buffer)[i]); + unselect(); + + /* no need to wait for transmit mode to be ready since its handled by the radio */ + setMode(RF69_MODE_TX); + while (digitalRead(_interruptPin) == 0); //wait for DIO0 to turn HIGH signalling transmission finish + //while (readReg(REG_IRQFLAGS2) & RF_IRQFLAGS2_PACKETSENT == 0x00); // Wait for ModeReady + setMode(RF69_MODE_STANDBY); +} + +void RFM69::interruptHandler() { + //pinMode(4, OUTPUT); + //digitalWrite(4, 1); + if (_mode == RF69_MODE_RX && (readReg(REG_IRQFLAGS2) & RF_IRQFLAGS2_PAYLOADREADY)) + { + //RSSI = readRSSI(); + setMode(RF69_MODE_STANDBY); + select(); + SPI.transfer(REG_FIFO & 0x7f); + PAYLOADLEN = SPI.transfer(0); + PAYLOADLEN = PAYLOADLEN > 66 ? 66 : PAYLOADLEN; //precaution + TARGETID = SPI.transfer(0); + if(!(_promiscuousMode || TARGETID==_address || TARGETID==RF69_BROADCAST_ADDR)) //match this node's address, or broadcast address or anything in promiscuous mode + { + PAYLOADLEN = 0; + unselect(); + //digitalWrite(4, 0); + return; + } + DATALEN = PAYLOADLEN - 3; + SENDERID = SPI.transfer(0); + byte CTLbyte = SPI.transfer(0); + + ACK_RECEIVED = CTLbyte & 0x80; //extract ACK-requested flag + ACK_REQUESTED = CTLbyte & 0x40; //extract ACK-received flag + + for (byte i= 0; i < DATALEN; i++) + { + DATA[i] = SPI.transfer(0); + } + if (DATALENinterruptHandler(); } + +void RFM69::receiveBegin() { + DATALEN = 0; + SENDERID = 0; + TARGETID = 0; + PAYLOADLEN = 0; + ACK_REQUESTED = 0; + ACK_RECEIVED = 0; + RSSI = 0; + if (readReg(REG_IRQFLAGS2) & RF_IRQFLAGS2_PAYLOADREADY) + writeReg(REG_PACKETCONFIG2, (readReg(REG_PACKETCONFIG2) & 0xFB) | RF_PACKET2_RXRESTART); // avoid RX deadlocks + writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_01); //set DIO0 to "PAYLOADREADY" in receive mode + setMode(RF69_MODE_RX); +} + +bool RFM69::receiveDone() { +// ATOMIC_BLOCK(ATOMIC_FORCEON) +// { + noInterrupts(); //re-enabled in unselect() via setMode() or via receiveBegin() + if (_mode == RF69_MODE_RX && PAYLOADLEN>0) + { + setMode(RF69_MODE_STANDBY); //enables interrupts + return true; + } + else if (_mode == RF69_MODE_RX) //already in RX no payload yet + { + interrupts(); //explicitly re-enable interrupts + return false; + } + receiveBegin(); + return false; +//} +} + +// To enable encryption: radio.encrypt("ABCDEFGHIJKLMNOP"); +// To disable encryption: radio.encrypt(null) or radio.encrypt(0) +// KEY HAS TO BE 16 bytes !!! +void RFM69::encrypt(const char* key) { + setMode(RF69_MODE_STANDBY); + if (key!=0) + { + select(); + SPI.transfer(REG_AESKEY1 | 0x80); + for (byte i = 0; i<16; i++) + SPI.transfer(key[i]); + unselect(); + } + writeReg(REG_PACKETCONFIG2, (readReg(REG_PACKETCONFIG2) & 0xFE) | (key ? 1 : 0)); +} + +int RFM69::readRSSI(bool forceTrigger) { + int rssi = 0; + if (forceTrigger) + { + //RSSI trigger not needed if DAGC is in continuous mode + writeReg(REG_RSSICONFIG, RF_RSSI_START); + while ((readReg(REG_RSSICONFIG) & RF_RSSI_DONE) == 0x00); // Wait for RSSI_Ready + } + rssi = -readReg(REG_RSSIVALUE); + rssi >>= 1; + return rssi; +} + +byte RFM69::readReg(byte addr) +{ + select(); + SPI.transfer(addr & 0x7F); + byte regval = SPI.transfer(0); + unselect(); + return regval; +} + +void RFM69::writeReg(byte addr, byte value) +{ + select(); + SPI.transfer(addr | 0x80); + SPI.transfer(value); + unselect(); +} + +/// Select the transceiver +void RFM69::select() { + noInterrupts(); + //save current SPI settings + _SPCR = SPCR; + _SPSR = SPSR; + //set RFM69 SPI settings + SPI.setDataMode(SPI_MODE0); + SPI.setBitOrder(MSBFIRST); + SPI.setClockDivider(SPI_CLOCK_DIV4); //decided to slow down from DIV2 after SPI stalling in some instances, especially visible on mega1284p when RFM69 and FLASH chip both present + digitalWrite(_slaveSelectPin, LOW); +} + +/// UNselect the transceiver chip +void RFM69::unselect() { + digitalWrite(_slaveSelectPin, HIGH); + //restore SPI settings to what they were before talking to RFM69 + SPCR = _SPCR; + SPSR = _SPSR; + interrupts(); +} + +// ON = disable filtering to capture all frames on network +// OFF = enable node+broadcast filtering to capture only frames sent to this/broadcast address +void RFM69::promiscuous(bool onOff) { + _promiscuousMode=onOff; + //writeReg(REG_PACKETCONFIG1, (readReg(REG_PACKETCONFIG1) & 0xF9) | (onOff ? RF_PACKET1_ADRSFILTERING_OFF : RF_PACKET1_ADRSFILTERING_NODEBROADCAST)); +} + +void RFM69::setHighPower(bool onOff) { + _isRFM69HW = onOff; + writeReg(REG_OCP, _isRFM69HW ? RF_OCP_OFF : RF_OCP_ON); + if (_isRFM69HW) //turning ON + writeReg(REG_PALEVEL, (readReg(REG_PALEVEL) & 0x1F) | RF_PALEVEL_PA1_ON | RF_PALEVEL_PA2_ON); //enable P1 & P2 amplifier stages + else + writeReg(REG_PALEVEL, RF_PALEVEL_PA0_ON | RF_PALEVEL_PA1_OFF | RF_PALEVEL_PA2_OFF | _powerLevel); //enable P0 only +} + +void RFM69::setHighPowerRegs(bool onOff) { + writeReg(REG_TESTPA1, onOff ? 0x5D : 0x55); + writeReg(REG_TESTPA2, onOff ? 0x7C : 0x70); +} + +void RFM69::setCS(byte newSPISlaveSelect) { + _slaveSelectPin = newSPISlaveSelect; + pinMode(_slaveSelectPin, OUTPUT); +} + +//for debugging +void RFM69::readAllRegs() +{ + byte regVal; + + for (byte regAddr = 1; regAddr <= 0x4F; regAddr++) + { + select(); + SPI.transfer(regAddr & 0x7f); // send address + r/w bit + regVal = SPI.transfer(0); + unselect(); + + Serial.print(regAddr, HEX); + Serial.print(" - "); + Serial.print(regVal,HEX); + Serial.print(" - "); + Serial.println(regVal,BIN); + } + unselect(); +} + +byte RFM69::readTemperature(byte calFactor) //returns centigrade +{ + setMode(RF69_MODE_STANDBY); + writeReg(REG_TEMP1, RF_TEMP1_MEAS_START); + while ((readReg(REG_TEMP1) & RF_TEMP1_MEAS_RUNNING)) Serial.print('*'); + return ~readReg(REG_TEMP2) + COURSE_TEMP_COEF + calFactor; //'complement'corrects the slope, rising temp = rising val +} // COURSE_TEMP_COEF puts reading in the ballpark, user can add additional correction + +void RFM69::rcCalibration() +{ + writeReg(REG_OSC1, RF_OSC1_RCCAL_START); + while ((readReg(REG_OSC1) & RF_OSC1_RCCAL_DONE) == 0x00); +} \ No newline at end of file diff --git a/libraries/MySensors/RFM69.h b/libraries/MySensors/RFM69.h new file mode 100644 index 0000000..23eb044 --- /dev/null +++ b/libraries/MySensors/RFM69.h @@ -0,0 +1,136 @@ +// ********************************************************************************** +// Driver definition for HopeRF RFM69W/RFM69HW/RFM69CW/RFM69HCW, Semtech SX1231/1231H +// ********************************************************************************** +// Copyright Felix Rusu (2014), felix@lowpowerlab.com +// http://lowpowerlab.com/ +// ********************************************************************************** +// License +// ********************************************************************************** +// This program is free software; you can redistribute it +// and/or modify it under the terms of the GNU General +// Public License as published by the Free Software +// Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will +// be useful, but WITHOUT ANY WARRANTY; without even the +// implied warranty of MERCHANTABILITY or FITNESS FOR A +// PARTICULAR PURPOSE. See the GNU General Public +// License for more details. +// +// You should have received a copy of the GNU General +// Public License along with this program; if not, write +// to the Free Software Foundation, Inc., +// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// Licence can be viewed at +// http://www.fsf.org/licenses/gpl.txt +// +// Please maintain this license information along with authorship +// and copyright notices in any redistribution of this code +// ********************************************************************************** +#ifndef RFM69_h +#define RFM69_h +#include //assumes Arduino IDE v1.0 or greater + +#define RF69_MAX_DATA_LEN 61 // to take advantage of the built in AES/CRC we want to limit the frame size to the internal FIFO size (66 bytes - 3 bytes overhead) +#define RF69_SPI_CS SS // SS is the SPI slave select pin, for instance D10 on atmega328 + +// INT0 on AVRs should be connected to RFM69's DIO0 (ex on Atmega328 it's D2, on Atmega644/1284 it's D2) +#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__) || defined(__AVR_ATmega32U4__) + #define RF69_IRQ_PIN 2 + #define RF69_IRQ_NUM 0 +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__) + #define RF69_IRQ_PIN 2 + #define RF69_IRQ_NUM 2 +#endif + +#define CSMA_LIMIT -90 // upper RX signal sensitivity threshold in dBm for carrier sense access +#define RF69_MODE_SLEEP 0 // XTAL OFF +#define RF69_MODE_STANDBY 1 // XTAL ON +#define RF69_MODE_SYNTH 2 // PLL ON +#define RF69_MODE_RX 3 // RX MODE +#define RF69_MODE_TX 4 // TX MODE + +//available frequency bands +#define RF69_315MHZ 31 // non trivial values to avoid misconfiguration +#define RF69_433MHZ 43 +#define RF69_868MHZ 86 +#define RF69_915MHZ 91 + +#define null 0 +#define COURSE_TEMP_COEF -90 // puts the temperature reading in the ballpark, user can fine tune the returned value +#define RF69_BROADCAST_ADDR 255 +#define RF69_CSMA_LIMIT_MS 1000 + +class RFM69 { + public: + static volatile byte DATA[RF69_MAX_DATA_LEN]; // recv/xmit buf, including hdr & crc bytes + static volatile byte DATALEN; + static volatile byte SENDERID; + static volatile byte TARGETID; //should match _address + static volatile byte PAYLOADLEN; + static volatile byte ACK_REQUESTED; + static volatile byte ACK_RECEIVED; /// Should be polled immediately after sending a packet with ACK request + static volatile int RSSI; //most accurate RSSI during reception (closest to the reception) + static volatile byte _mode; //should be protected? + + RFM69(byte slaveSelectPin=RF69_SPI_CS, byte interruptPin=RF69_IRQ_PIN, bool isRFM69HW=false, byte interruptNum=RF69_IRQ_NUM) { + _slaveSelectPin = slaveSelectPin; + _interruptPin = interruptPin; + _interruptNum = interruptNum; + _mode = RF69_MODE_STANDBY; + _promiscuousMode = false; + _powerLevel = 31; + _isRFM69HW = isRFM69HW; + } + + bool initialize(byte freqBand, byte ID, byte networkID=1); + void setAddress(byte addr); + bool canSend(); + void send(byte toAddress, const void* buffer, byte bufferSize, bool requestACK=false); + bool sendWithRetry(byte toAddress, const void* buffer, byte bufferSize, byte retries=2, byte retryWaitTime=40); //40ms roundtrip req for 61byte packets + bool receiveDone(); + bool ACKReceived(byte fromNodeID); + bool ACKRequested(); + void sendACK(const void* buffer = "", uint8_t bufferSize=0); + void setFrequency(uint32_t FRF); + void encrypt(const char* key); + void setCS(byte newSPISlaveSelect); + int readRSSI(bool forceTrigger=false); + void promiscuous(bool onOff=true); + void setHighPower(bool onOFF=true); //have to call it after initialize for RFM69HW + void setPowerLevel(byte level); //reduce/increase transmit power level + void sleep(); + byte readTemperature(byte calFactor=0); //get CMOS temperature (8bit) + void rcCalibration(); //calibrate the internal RC oscillator for use in wide temperature variations - see datasheet section [4.3.5. RC Timer Accuracy] + + // allow hacking registers by making these public + byte readReg(byte addr); + void writeReg(byte addr, byte val); + void readAllRegs(); + + protected: + static void isr0(); + void virtual interruptHandler(); + void sendFrame(byte toAddress, const void* buffer, byte size, bool requestACK=false, bool sendACK=false); + + static RFM69* selfPointer; + byte _slaveSelectPin; + byte _interruptPin; + byte _interruptNum; + byte _address; + bool _promiscuousMode; + byte _powerLevel; + bool _isRFM69HW; + byte _SPCR; + byte _SPSR; + + void receiveBegin(); + void setMode(byte mode); + void setHighPowerRegs(bool onOff); + void select(); + void unselect(); +}; + +#endif diff --git a/libraries/MySensors/RFM69registers.h b/libraries/MySensors/RFM69registers.h new file mode 100644 index 0000000..ff720b1 --- /dev/null +++ b/libraries/MySensors/RFM69registers.h @@ -0,0 +1,1069 @@ +// ********************************************************************************** +// Registers used in driver definition for HopeRF RFM69W/RFM69HW, Semtech SX1231/1231H +// ********************************************************************************** +// Copyright Felix Rusu (2014), felix@lowpowerlab.com +// http://lowpowerlab.com/ +// ********************************************************************************** +// License +// ********************************************************************************** +// This program is free software; you can redistribute it +// and/or modify it under the terms of the GNU General +// Public License as published by the Free Software +// Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will +// be useful, but WITHOUT ANY WARRANTY; without even the +// implied warranty of MERCHANTABILITY or FITNESS FOR A +// PARTICULAR PURPOSE. See the GNU General Public +// License for more details. +// +// You should have received a copy of the GNU General +// Public License along with this program; if not, write +// to the Free Software Foundation, Inc., +// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// Licence can be viewed at +// http://www.fsf.org/licenses/gpl.txt +// +// Please maintain this license information along with authorship +// and copyright notices in any redistribution of this code +// ********************************************************************************** +// RFM69/SX1231 Internal registers addresses +//************************************************** +#define REG_FIFO 0x00 +#define REG_OPMODE 0x01 +#define REG_DATAMODUL 0x02 +#define REG_BITRATEMSB 0x03 +#define REG_BITRATELSB 0x04 +#define REG_FDEVMSB 0x05 +#define REG_FDEVLSB 0x06 +#define REG_FRFMSB 0x07 +#define REG_FRFMID 0x08 +#define REG_FRFLSB 0x09 +#define REG_OSC1 0x0A +#define REG_AFCCTRL 0x0B +#define REG_LOWBAT 0x0C +#define REG_LISTEN1 0x0D +#define REG_LISTEN2 0x0E +#define REG_LISTEN3 0x0F +#define REG_VERSION 0x10 +#define REG_PALEVEL 0x11 +#define REG_PARAMP 0x12 +#define REG_OCP 0x13 +#define REG_AGCREF 0x14 +#define REG_AGCTHRESH1 0x15 +#define REG_AGCTHRESH2 0x16 +#define REG_AGCTHRESH3 0x17 +#define REG_LNA 0x18 +#define REG_RXBW 0x19 +#define REG_AFCBW 0x1A +#define REG_OOKPEAK 0x1B +#define REG_OOKAVG 0x1C +#define REG_OOKFIX 0x1D +#define REG_AFCFEI 0x1E +#define REG_AFCMSB 0x1F +#define REG_AFCLSB 0x20 +#define REG_FEIMSB 0x21 +#define REG_FEILSB 0x22 +#define REG_RSSICONFIG 0x23 +#define REG_RSSIVALUE 0x24 +#define REG_DIOMAPPING1 0x25 +#define REG_DIOMAPPING2 0x26 +#define REG_IRQFLAGS1 0x27 +#define REG_IRQFLAGS2 0x28 +#define REG_RSSITHRESH 0x29 +#define REG_RXTIMEOUT1 0x2A +#define REG_RXTIMEOUT2 0x2B +#define REG_PREAMBLEMSB 0x2C +#define REG_PREAMBLELSB 0x2D +#define REG_SYNCCONFIG 0x2E +#define REG_SYNCVALUE1 0x2F +#define REG_SYNCVALUE2 0x30 +#define REG_SYNCVALUE3 0x31 +#define REG_SYNCVALUE4 0x32 +#define REG_SYNCVALUE5 0x33 +#define REG_SYNCVALUE6 0x34 +#define REG_SYNCVALUE7 0x35 +#define REG_SYNCVALUE8 0x36 +#define REG_PACKETCONFIG1 0x37 +#define REG_PAYLOADLENGTH 0x38 +#define REG_NODEADRS 0x39 +#define REG_BROADCASTADRS 0x3A +#define REG_AUTOMODES 0x3B +#define REG_FIFOTHRESH 0x3C +#define REG_PACKETCONFIG2 0x3D +#define REG_AESKEY1 0x3E +#define REG_AESKEY2 0x3F +#define REG_AESKEY3 0x40 +#define REG_AESKEY4 0x41 +#define REG_AESKEY5 0x42 +#define REG_AESKEY6 0x43 +#define REG_AESKEY7 0x44 +#define REG_AESKEY8 0x45 +#define REG_AESKEY9 0x46 +#define REG_AESKEY10 0x47 +#define REG_AESKEY11 0x48 +#define REG_AESKEY12 0x49 +#define REG_AESKEY13 0x4A +#define REG_AESKEY14 0x4B +#define REG_AESKEY15 0x4C +#define REG_AESKEY16 0x4D +#define REG_TEMP1 0x4E +#define REG_TEMP2 0x4F +#define REG_TESTPA1 0x5A //only present on RFM69HW/SX1231H +#define REG_TESTPA2 0x5C //only present on RFM69HW/SX1231H +#define REG_TESTDAGC 0x6F + +//****************************************************** +// RF69/SX1231 bit control definition +//****************************************************** +// RegOpMode +#define RF_OPMODE_SEQUENCER_OFF 0x80 +#define RF_OPMODE_SEQUENCER_ON 0x00 // Default + +#define RF_OPMODE_LISTEN_ON 0x40 +#define RF_OPMODE_LISTEN_OFF 0x00 // Default + +#define RF_OPMODE_LISTENABORT 0x20 + +#define RF_OPMODE_SLEEP 0x00 +#define RF_OPMODE_STANDBY 0x04 // Default +#define RF_OPMODE_SYNTHESIZER 0x08 +#define RF_OPMODE_TRANSMITTER 0x0C +#define RF_OPMODE_RECEIVER 0x10 + +// RegDataModul +#define RF_DATAMODUL_DATAMODE_PACKET 0x00 // Default +#define RF_DATAMODUL_DATAMODE_CONTINUOUS 0x40 +#define RF_DATAMODUL_DATAMODE_CONTINUOUSNOBSYNC 0x60 + +#define RF_DATAMODUL_MODULATIONTYPE_FSK 0x00 // Default +#define RF_DATAMODUL_MODULATIONTYPE_OOK 0x08 + +#define RF_DATAMODUL_MODULATIONSHAPING_00 0x00 // Default +#define RF_DATAMODUL_MODULATIONSHAPING_01 0x01 +#define RF_DATAMODUL_MODULATIONSHAPING_10 0x02 +#define RF_DATAMODUL_MODULATIONSHAPING_11 0x03 + +// RegBitRate (bits/sec) example bit rates +#define RF_BITRATEMSB_1200 0x68 +#define RF_BITRATELSB_1200 0x2B +#define RF_BITRATEMSB_2400 0x34 +#define RF_BITRATELSB_2400 0x15 +#define RF_BITRATEMSB_4800 0x1A // Default +#define RF_BITRATELSB_4800 0x0B // Default +#define RF_BITRATEMSB_9600 0x0D +#define RF_BITRATELSB_9600 0x05 +#define RF_BITRATEMSB_19200 0x06 +#define RF_BITRATELSB_19200 0x83 +#define RF_BITRATEMSB_38400 0x03 +#define RF_BITRATELSB_38400 0x41 + +#define RF_BITRATEMSB_38323 0x03 +#define RF_BITRATELSB_38323 0x43 + +#define RF_BITRATEMSB_34482 0x03 +#define RF_BITRATELSB_34482 0xA0 + +#define RF_BITRATEMSB_76800 0x01 +#define RF_BITRATELSB_76800 0xA1 +#define RF_BITRATEMSB_153600 0x00 +#define RF_BITRATELSB_153600 0xD0 +#define RF_BITRATEMSB_57600 0x02 +#define RF_BITRATELSB_57600 0x2C +#define RF_BITRATEMSB_115200 0x01 +#define RF_BITRATELSB_115200 0x16 +#define RF_BITRATEMSB_12500 0x0A +#define RF_BITRATELSB_12500 0x00 +#define RF_BITRATEMSB_25000 0x05 +#define RF_BITRATELSB_25000 0x00 +#define RF_BITRATEMSB_50000 0x02 +#define RF_BITRATELSB_50000 0x80 +#define RF_BITRATEMSB_100000 0x01 +#define RF_BITRATELSB_100000 0x40 +#define RF_BITRATEMSB_150000 0x00 +#define RF_BITRATELSB_150000 0xD5 +#define RF_BITRATEMSB_200000 0x00 +#define RF_BITRATELSB_200000 0xA0 +#define RF_BITRATEMSB_250000 0x00 +#define RF_BITRATELSB_250000 0x80 +#define RF_BITRATEMSB_300000 0x00 +#define RF_BITRATELSB_300000 0x6B +#define RF_BITRATEMSB_32768 0x03 +#define RF_BITRATELSB_32768 0xD1 +//custom bit rates +#define RF_BITRATEMSB_55555 0x02 +#define RF_BITRATELSB_55555 0x40 +#define RF_BITRATEMSB_200KBPS 0x00 +#define RF_BITRATELSB_200KBPS 0xa0 + +// RegFdev - frequency deviation (Hz) +#define RF_FDEVMSB_2000 0x00 +#define RF_FDEVLSB_2000 0x21 +#define RF_FDEVMSB_5000 0x00 // Default +#define RF_FDEVLSB_5000 0x52 // Default +#define RF_FDEVMSB_7500 0x00 +#define RF_FDEVLSB_7500 0x7B +#define RF_FDEVMSB_10000 0x00 +#define RF_FDEVLSB_10000 0xA4 +#define RF_FDEVMSB_15000 0x00 +#define RF_FDEVLSB_15000 0xF6 +#define RF_FDEVMSB_20000 0x01 +#define RF_FDEVLSB_20000 0x48 +#define RF_FDEVMSB_25000 0x01 +#define RF_FDEVLSB_25000 0x9A +#define RF_FDEVMSB_30000 0x01 +#define RF_FDEVLSB_30000 0xEC +#define RF_FDEVMSB_35000 0x02 +#define RF_FDEVLSB_35000 0x3D +#define RF_FDEVMSB_40000 0x02 +#define RF_FDEVLSB_40000 0x8F +#define RF_FDEVMSB_45000 0x02 +#define RF_FDEVLSB_45000 0xE1 +#define RF_FDEVMSB_50000 0x03 +#define RF_FDEVLSB_50000 0x33 +#define RF_FDEVMSB_55000 0x03 +#define RF_FDEVLSB_55000 0x85 +#define RF_FDEVMSB_60000 0x03 +#define RF_FDEVLSB_60000 0xD7 +#define RF_FDEVMSB_65000 0x04 +#define RF_FDEVLSB_65000 0x29 +#define RF_FDEVMSB_70000 0x04 +#define RF_FDEVLSB_70000 0x7B +#define RF_FDEVMSB_75000 0x04 +#define RF_FDEVLSB_75000 0xCD +#define RF_FDEVMSB_80000 0x05 +#define RF_FDEVLSB_80000 0x1F +#define RF_FDEVMSB_85000 0x05 +#define RF_FDEVLSB_85000 0x71 +#define RF_FDEVMSB_90000 0x05 +#define RF_FDEVLSB_90000 0xC3 +#define RF_FDEVMSB_95000 0x06 +#define RF_FDEVLSB_95000 0x14 +#define RF_FDEVMSB_100000 0x06 +#define RF_FDEVLSB_100000 0x66 +#define RF_FDEVMSB_110000 0x07 +#define RF_FDEVLSB_110000 0x0A +#define RF_FDEVMSB_120000 0x07 +#define RF_FDEVLSB_120000 0xAE +#define RF_FDEVMSB_130000 0x08 +#define RF_FDEVLSB_130000 0x52 +#define RF_FDEVMSB_140000 0x08 +#define RF_FDEVLSB_140000 0xF6 +#define RF_FDEVMSB_150000 0x09 +#define RF_FDEVLSB_150000 0x9A +#define RF_FDEVMSB_160000 0x0A +#define RF_FDEVLSB_160000 0x3D +#define RF_FDEVMSB_170000 0x0A +#define RF_FDEVLSB_170000 0xE1 +#define RF_FDEVMSB_180000 0x0B +#define RF_FDEVLSB_180000 0x85 +#define RF_FDEVMSB_190000 0x0C +#define RF_FDEVLSB_190000 0x29 +#define RF_FDEVMSB_200000 0x0C +#define RF_FDEVLSB_200000 0xCD +#define RF_FDEVMSB_210000 0x0D +#define RF_FDEVLSB_210000 0x71 +#define RF_FDEVMSB_220000 0x0E +#define RF_FDEVLSB_220000 0x14 +#define RF_FDEVMSB_230000 0x0E +#define RF_FDEVLSB_230000 0xB8 +#define RF_FDEVMSB_240000 0x0F +#define RF_FDEVLSB_240000 0x5C +#define RF_FDEVMSB_250000 0x10 +#define RF_FDEVLSB_250000 0x00 +#define RF_FDEVMSB_260000 0x10 +#define RF_FDEVLSB_260000 0xA4 +#define RF_FDEVMSB_270000 0x11 +#define RF_FDEVLSB_270000 0x48 +#define RF_FDEVMSB_280000 0x11 +#define RF_FDEVLSB_280000 0xEC +#define RF_FDEVMSB_290000 0x12 +#define RF_FDEVLSB_290000 0x8F +#define RF_FDEVMSB_300000 0x13 +#define RF_FDEVLSB_300000 0x33 + +// RegFrf (MHz) - carrier frequency +// 315Mhz band +#define RF_FRFMSB_314 0x4E +#define RF_FRFMID_314 0x80 +#define RF_FRFLSB_314 0x00 +#define RF_FRFMSB_315 0x4E +#define RF_FRFMID_315 0xC0 +#define RF_FRFLSB_315 0x00 +#define RF_FRFMSB_316 0x4F +#define RF_FRFMID_316 0x00 +#define RF_FRFLSB_316 0x00 +// 433mhz band +#define RF_FRFMSB_433 0x6C +#define RF_FRFMID_433 0x40 +#define RF_FRFLSB_433 0x00 +#define RF_FRFMSB_434 0x6C +#define RF_FRFMID_434 0x80 +#define RF_FRFLSB_434 0x00 +#define RF_FRFMSB_435 0x6C +#define RF_FRFMID_435 0xC0 +#define RF_FRFLSB_435 0x00 +// 868Mhz band +#define RF_FRFMSB_863 0xD7 +#define RF_FRFMID_863 0xC0 +#define RF_FRFLSB_863 0x00 +#define RF_FRFMSB_864 0xD8 +#define RF_FRFMID_864 0x00 +#define RF_FRFLSB_864 0x00 +#define RF_FRFMSB_865 0xD8 +#define RF_FRFMID_865 0x40 +#define RF_FRFLSB_865 0x00 +#define RF_FRFMSB_866 0xD8 +#define RF_FRFMID_866 0x80 +#define RF_FRFLSB_866 0x00 +#define RF_FRFMSB_867 0xD8 +#define RF_FRFMID_867 0xC0 +#define RF_FRFLSB_867 0x00 +#define RF_FRFMSB_868 0xD9 +#define RF_FRFMID_868 0x00 +#define RF_FRFLSB_868 0x00 +#define RF_FRFMSB_869 0xD9 +#define RF_FRFMID_869 0x40 +#define RF_FRFLSB_869 0x00 +#define RF_FRFMSB_870 0xD9 +#define RF_FRFMID_870 0x80 +#define RF_FRFLSB_870 0x00 +// 915Mhz band +#define RF_FRFMSB_902 0xE1 +#define RF_FRFMID_902 0x80 +#define RF_FRFLSB_902 0x00 +#define RF_FRFMSB_903 0xE1 +#define RF_FRFMID_903 0xC0 +#define RF_FRFLSB_903 0x00 +#define RF_FRFMSB_904 0xE2 +#define RF_FRFMID_904 0x00 +#define RF_FRFLSB_904 0x00 +#define RF_FRFMSB_905 0xE2 +#define RF_FRFMID_905 0x40 +#define RF_FRFLSB_905 0x00 +#define RF_FRFMSB_906 0xE2 +#define RF_FRFMID_906 0x80 +#define RF_FRFLSB_906 0x00 +#define RF_FRFMSB_907 0xE2 +#define RF_FRFMID_907 0xC0 +#define RF_FRFLSB_907 0x00 +#define RF_FRFMSB_908 0xE3 +#define RF_FRFMID_908 0x00 +#define RF_FRFLSB_908 0x00 +#define RF_FRFMSB_909 0xE3 +#define RF_FRFMID_909 0x40 +#define RF_FRFLSB_909 0x00 +#define RF_FRFMSB_910 0xE3 +#define RF_FRFMID_910 0x80 +#define RF_FRFLSB_910 0x00 +#define RF_FRFMSB_911 0xE3 +#define RF_FRFMID_911 0xC0 +#define RF_FRFLSB_911 0x00 +#define RF_FRFMSB_912 0xE4 +#define RF_FRFMID_912 0x00 +#define RF_FRFLSB_912 0x00 +#define RF_FRFMSB_913 0xE4 +#define RF_FRFMID_913 0x40 +#define RF_FRFLSB_913 0x00 +#define RF_FRFMSB_914 0xE4 +#define RF_FRFMID_914 0x80 +#define RF_FRFLSB_914 0x00 +#define RF_FRFMSB_915 0xE4 // Default +#define RF_FRFMID_915 0xC0 // Default +#define RF_FRFLSB_915 0x00 // Default +#define RF_FRFMSB_916 0xE5 +#define RF_FRFMID_916 0x00 +#define RF_FRFLSB_916 0x00 +#define RF_FRFMSB_917 0xE5 +#define RF_FRFMID_917 0x40 +#define RF_FRFLSB_917 0x00 +#define RF_FRFMSB_918 0xE5 +#define RF_FRFMID_918 0x80 +#define RF_FRFLSB_918 0x00 +#define RF_FRFMSB_919 0xE5 +#define RF_FRFMID_919 0xC0 +#define RF_FRFLSB_919 0x00 +#define RF_FRFMSB_920 0xE6 +#define RF_FRFMID_920 0x00 +#define RF_FRFLSB_920 0x00 +#define RF_FRFMSB_921 0xE6 +#define RF_FRFMID_921 0x40 +#define RF_FRFLSB_921 0x00 +#define RF_FRFMSB_922 0xE6 +#define RF_FRFMID_922 0x80 +#define RF_FRFLSB_922 0x00 +#define RF_FRFMSB_923 0xE6 +#define RF_FRFMID_923 0xC0 +#define RF_FRFLSB_923 0x00 +#define RF_FRFMSB_924 0xE7 +#define RF_FRFMID_924 0x00 +#define RF_FRFLSB_924 0x00 +#define RF_FRFMSB_925 0xE7 +#define RF_FRFMID_925 0x40 +#define RF_FRFLSB_925 0x00 +#define RF_FRFMSB_926 0xE7 +#define RF_FRFMID_926 0x80 +#define RF_FRFLSB_926 0x00 +#define RF_FRFMSB_927 0xE7 +#define RF_FRFMID_927 0xC0 +#define RF_FRFLSB_927 0x00 +#define RF_FRFMSB_928 0xE8 +#define RF_FRFMID_928 0x00 +#define RF_FRFLSB_928 0x00 + + +// RegOsc1 +#define RF_OSC1_RCCAL_START 0x80 +#define RF_OSC1_RCCAL_DONE 0x40 + +// RegLowBat +#define RF_LOWBAT_MONITOR 0x10 +#define RF_LOWBAT_ON 0x08 +#define RF_LOWBAT_OFF 0x00 // Default + +#define RF_LOWBAT_TRIM_1695 0x00 +#define RF_LOWBAT_TRIM_1764 0x01 +#define RF_LOWBAT_TRIM_1835 0x02 // Default +#define RF_LOWBAT_TRIM_1905 0x03 +#define RF_LOWBAT_TRIM_1976 0x04 +#define RF_LOWBAT_TRIM_2045 0x05 +#define RF_LOWBAT_TRIM_2116 0x06 +#define RF_LOWBAT_TRIM_2185 0x07 + + +// RegListen1 +#define RF_LISTEN1_RESOL_64 0x50 +#define RF_LISTEN1_RESOL_4100 0xA0 // Default +#define RF_LISTEN1_RESOL_262000 0xF0 + +#define RF_LISTEN1_CRITERIA_RSSI 0x00 // Default +#define RF_LISTEN1_CRITERIA_RSSIANDSYNC 0x08 + +#define RF_LISTEN1_END_00 0x00 +#define RF_LISTEN1_END_01 0x02 // Default +#define RF_LISTEN1_END_10 0x04 + + +// RegListen2 +#define RF_LISTEN2_COEFIDLE_VALUE 0xF5 // Default + +// RegListen3 +#define RF_LISTEN3_COEFRX_VALUE 0x20 // Default + +// RegPaLevel +#define RF_PALEVEL_PA0_ON 0x80 // Default +#define RF_PALEVEL_PA0_OFF 0x00 +#define RF_PALEVEL_PA1_ON 0x40 +#define RF_PALEVEL_PA1_OFF 0x00 // Default +#define RF_PALEVEL_PA2_ON 0x20 +#define RF_PALEVEL_PA2_OFF 0x00 // Default + +#define RF_PALEVEL_OUTPUTPOWER_00000 0x00 +#define RF_PALEVEL_OUTPUTPOWER_00001 0x01 +#define RF_PALEVEL_OUTPUTPOWER_00010 0x02 +#define RF_PALEVEL_OUTPUTPOWER_00011 0x03 +#define RF_PALEVEL_OUTPUTPOWER_00100 0x04 +#define RF_PALEVEL_OUTPUTPOWER_00101 0x05 +#define RF_PALEVEL_OUTPUTPOWER_00110 0x06 +#define RF_PALEVEL_OUTPUTPOWER_00111 0x07 +#define RF_PALEVEL_OUTPUTPOWER_01000 0x08 +#define RF_PALEVEL_OUTPUTPOWER_01001 0x09 +#define RF_PALEVEL_OUTPUTPOWER_01010 0x0A +#define RF_PALEVEL_OUTPUTPOWER_01011 0x0B +#define RF_PALEVEL_OUTPUTPOWER_01100 0x0C +#define RF_PALEVEL_OUTPUTPOWER_01101 0x0D +#define RF_PALEVEL_OUTPUTPOWER_01110 0x0E +#define RF_PALEVEL_OUTPUTPOWER_01111 0x0F +#define RF_PALEVEL_OUTPUTPOWER_10000 0x10 +#define RF_PALEVEL_OUTPUTPOWER_10001 0x11 +#define RF_PALEVEL_OUTPUTPOWER_10010 0x12 +#define RF_PALEVEL_OUTPUTPOWER_10011 0x13 +#define RF_PALEVEL_OUTPUTPOWER_10100 0x14 +#define RF_PALEVEL_OUTPUTPOWER_10101 0x15 +#define RF_PALEVEL_OUTPUTPOWER_10110 0x16 +#define RF_PALEVEL_OUTPUTPOWER_10111 0x17 +#define RF_PALEVEL_OUTPUTPOWER_11000 0x18 +#define RF_PALEVEL_OUTPUTPOWER_11001 0x19 +#define RF_PALEVEL_OUTPUTPOWER_11010 0x1A +#define RF_PALEVEL_OUTPUTPOWER_11011 0x1B +#define RF_PALEVEL_OUTPUTPOWER_11100 0x1C +#define RF_PALEVEL_OUTPUTPOWER_11101 0x1D +#define RF_PALEVEL_OUTPUTPOWER_11110 0x1E +#define RF_PALEVEL_OUTPUTPOWER_11111 0x1F // Default + + +// RegPaRamp +#define RF_PARAMP_3400 0x00 +#define RF_PARAMP_2000 0x01 +#define RF_PARAMP_1000 0x02 +#define RF_PARAMP_500 0x03 +#define RF_PARAMP_250 0x04 +#define RF_PARAMP_125 0x05 +#define RF_PARAMP_100 0x06 +#define RF_PARAMP_62 0x07 +#define RF_PARAMP_50 0x08 +#define RF_PARAMP_40 0x09 // Default +#define RF_PARAMP_31 0x0A +#define RF_PARAMP_25 0x0B +#define RF_PARAMP_20 0x0C +#define RF_PARAMP_15 0x0D +#define RF_PARAMP_12 0x0E +#define RF_PARAMP_10 0x0F + + +// RegOcp +#define RF_OCP_OFF 0x0F +#define RF_OCP_ON 0x1A // Default + +#define RF_OCP_TRIM_45 0x00 +#define RF_OCP_TRIM_50 0x01 +#define RF_OCP_TRIM_55 0x02 +#define RF_OCP_TRIM_60 0x03 +#define RF_OCP_TRIM_65 0x04 +#define RF_OCP_TRIM_70 0x05 +#define RF_OCP_TRIM_75 0x06 +#define RF_OCP_TRIM_80 0x07 +#define RF_OCP_TRIM_85 0x08 +#define RF_OCP_TRIM_90 0x09 +#define RF_OCP_TRIM_95 0x0A +#define RF_OCP_TRIM_100 0x0B // Default +#define RF_OCP_TRIM_105 0x0C +#define RF_OCP_TRIM_110 0x0D +#define RF_OCP_TRIM_115 0x0E +#define RF_OCP_TRIM_120 0x0F + + +// RegAgcRef +#define RF_AGCREF_AUTO_ON 0x40 // Default +#define RF_AGCREF_AUTO_OFF 0x00 + +#define RF_AGCREF_LEVEL_MINUS80 0x00 // Default +#define RF_AGCREF_LEVEL_MINUS81 0x01 +#define RF_AGCREF_LEVEL_MINUS82 0x02 +#define RF_AGCREF_LEVEL_MINUS83 0x03 +#define RF_AGCREF_LEVEL_MINUS84 0x04 +#define RF_AGCREF_LEVEL_MINUS85 0x05 +#define RF_AGCREF_LEVEL_MINUS86 0x06 +#define RF_AGCREF_LEVEL_MINUS87 0x07 +#define RF_AGCREF_LEVEL_MINUS88 0x08 +#define RF_AGCREF_LEVEL_MINUS89 0x09 +#define RF_AGCREF_LEVEL_MINUS90 0x0A +#define RF_AGCREF_LEVEL_MINUS91 0x0B +#define RF_AGCREF_LEVEL_MINUS92 0x0C +#define RF_AGCREF_LEVEL_MINUS93 0x0D +#define RF_AGCREF_LEVEL_MINUS94 0x0E +#define RF_AGCREF_LEVEL_MINUS95 0x0F +#define RF_AGCREF_LEVEL_MINUS96 0x10 +#define RF_AGCREF_LEVEL_MINUS97 0x11 +#define RF_AGCREF_LEVEL_MINUS98 0x12 +#define RF_AGCREF_LEVEL_MINUS99 0x13 +#define RF_AGCREF_LEVEL_MINUS100 0x14 +#define RF_AGCREF_LEVEL_MINUS101 0x15 +#define RF_AGCREF_LEVEL_MINUS102 0x16 +#define RF_AGCREF_LEVEL_MINUS103 0x17 +#define RF_AGCREF_LEVEL_MINUS104 0x18 +#define RF_AGCREF_LEVEL_MINUS105 0x19 +#define RF_AGCREF_LEVEL_MINUS106 0x1A +#define RF_AGCREF_LEVEL_MINUS107 0x1B +#define RF_AGCREF_LEVEL_MINUS108 0x1C +#define RF_AGCREF_LEVEL_MINUS109 0x1D +#define RF_AGCREF_LEVEL_MINUS110 0x1E +#define RF_AGCREF_LEVEL_MINUS111 0x1F +#define RF_AGCREF_LEVEL_MINUS112 0x20 +#define RF_AGCREF_LEVEL_MINUS113 0x21 +#define RF_AGCREF_LEVEL_MINUS114 0x22 +#define RF_AGCREF_LEVEL_MINUS115 0x23 +#define RF_AGCREF_LEVEL_MINUS116 0x24 +#define RF_AGCREF_LEVEL_MINUS117 0x25 +#define RF_AGCREF_LEVEL_MINUS118 0x26 +#define RF_AGCREF_LEVEL_MINUS119 0x27 +#define RF_AGCREF_LEVEL_MINUS120 0x28 +#define RF_AGCREF_LEVEL_MINUS121 0x29 +#define RF_AGCREF_LEVEL_MINUS122 0x2A +#define RF_AGCREF_LEVEL_MINUS123 0x2B +#define RF_AGCREF_LEVEL_MINUS124 0x2C +#define RF_AGCREF_LEVEL_MINUS125 0x2D +#define RF_AGCREF_LEVEL_MINUS126 0x2E +#define RF_AGCREF_LEVEL_MINUS127 0x2F +#define RF_AGCREF_LEVEL_MINUS128 0x30 +#define RF_AGCREF_LEVEL_MINUS129 0x31 +#define RF_AGCREF_LEVEL_MINUS130 0x32 +#define RF_AGCREF_LEVEL_MINUS131 0x33 +#define RF_AGCREF_LEVEL_MINUS132 0x34 +#define RF_AGCREF_LEVEL_MINUS133 0x35 +#define RF_AGCREF_LEVEL_MINUS134 0x36 +#define RF_AGCREF_LEVEL_MINUS135 0x37 +#define RF_AGCREF_LEVEL_MINUS136 0x38 +#define RF_AGCREF_LEVEL_MINUS137 0x39 +#define RF_AGCREF_LEVEL_MINUS138 0x3A +#define RF_AGCREF_LEVEL_MINUS139 0x3B +#define RF_AGCREF_LEVEL_MINUS140 0x3C +#define RF_AGCREF_LEVEL_MINUS141 0x3D +#define RF_AGCREF_LEVEL_MINUS142 0x3E +#define RF_AGCREF_LEVEL_MINUS143 0x3F + + +// RegAgcThresh1 +#define RF_AGCTHRESH1_SNRMARGIN_000 0x00 +#define RF_AGCTHRESH1_SNRMARGIN_001 0x20 +#define RF_AGCTHRESH1_SNRMARGIN_010 0x40 +#define RF_AGCTHRESH1_SNRMARGIN_011 0x60 +#define RF_AGCTHRESH1_SNRMARGIN_100 0x80 +#define RF_AGCTHRESH1_SNRMARGIN_101 0xA0 // Default +#define RF_AGCTHRESH1_SNRMARGIN_110 0xC0 +#define RF_AGCTHRESH1_SNRMARGIN_111 0xE0 + +#define RF_AGCTHRESH1_STEP1_0 0x00 +#define RF_AGCTHRESH1_STEP1_1 0x01 +#define RF_AGCTHRESH1_STEP1_2 0x02 +#define RF_AGCTHRESH1_STEP1_3 0x03 +#define RF_AGCTHRESH1_STEP1_4 0x04 +#define RF_AGCTHRESH1_STEP1_5 0x05 +#define RF_AGCTHRESH1_STEP1_6 0x06 +#define RF_AGCTHRESH1_STEP1_7 0x07 +#define RF_AGCTHRESH1_STEP1_8 0x08 +#define RF_AGCTHRESH1_STEP1_9 0x09 +#define RF_AGCTHRESH1_STEP1_10 0x0A +#define RF_AGCTHRESH1_STEP1_11 0x0B +#define RF_AGCTHRESH1_STEP1_12 0x0C +#define RF_AGCTHRESH1_STEP1_13 0x0D +#define RF_AGCTHRESH1_STEP1_14 0x0E +#define RF_AGCTHRESH1_STEP1_15 0x0F +#define RF_AGCTHRESH1_STEP1_16 0x10 // Default +#define RF_AGCTHRESH1_STEP1_17 0x11 +#define RF_AGCTHRESH1_STEP1_18 0x12 +#define RF_AGCTHRESH1_STEP1_19 0x13 +#define RF_AGCTHRESH1_STEP1_20 0x14 +#define RF_AGCTHRESH1_STEP1_21 0x15 +#define RF_AGCTHRESH1_STEP1_22 0x16 +#define RF_AGCTHRESH1_STEP1_23 0x17 +#define RF_AGCTHRESH1_STEP1_24 0x18 +#define RF_AGCTHRESH1_STEP1_25 0x19 +#define RF_AGCTHRESH1_STEP1_26 0x1A +#define RF_AGCTHRESH1_STEP1_27 0x1B +#define RF_AGCTHRESH1_STEP1_28 0x1C +#define RF_AGCTHRESH1_STEP1_29 0x1D +#define RF_AGCTHRESH1_STEP1_30 0x1E +#define RF_AGCTHRESH1_STEP1_31 0x1F + + +// RegAgcThresh2 +#define RF_AGCTHRESH2_STEP2_0 0x00 +#define RF_AGCTHRESH2_STEP2_1 0x10 +#define RF_AGCTHRESH2_STEP2_2 0x20 +#define RF_AGCTHRESH2_STEP2_3 0x30 // XXX wrong -- Default +#define RF_AGCTHRESH2_STEP2_4 0x40 +#define RF_AGCTHRESH2_STEP2_5 0x50 +#define RF_AGCTHRESH2_STEP2_6 0x60 +#define RF_AGCTHRESH2_STEP2_7 0x70 // default +#define RF_AGCTHRESH2_STEP2_8 0x80 +#define RF_AGCTHRESH2_STEP2_9 0x90 +#define RF_AGCTHRESH2_STEP2_10 0xA0 +#define RF_AGCTHRESH2_STEP2_11 0xB0 +#define RF_AGCTHRESH2_STEP2_12 0xC0 +#define RF_AGCTHRESH2_STEP2_13 0xD0 +#define RF_AGCTHRESH2_STEP2_14 0xE0 +#define RF_AGCTHRESH2_STEP2_15 0xF0 + +#define RF_AGCTHRESH2_STEP3_0 0x00 +#define RF_AGCTHRESH2_STEP3_1 0x01 +#define RF_AGCTHRESH2_STEP3_2 0x02 +#define RF_AGCTHRESH2_STEP3_3 0x03 +#define RF_AGCTHRESH2_STEP3_4 0x04 +#define RF_AGCTHRESH2_STEP3_5 0x05 +#define RF_AGCTHRESH2_STEP3_6 0x06 +#define RF_AGCTHRESH2_STEP3_7 0x07 +#define RF_AGCTHRESH2_STEP3_8 0x08 +#define RF_AGCTHRESH2_STEP3_9 0x09 +#define RF_AGCTHRESH2_STEP3_10 0x0A +#define RF_AGCTHRESH2_STEP3_11 0x0B // Default +#define RF_AGCTHRESH2_STEP3_12 0x0C +#define RF_AGCTHRESH2_STEP3_13 0x0D +#define RF_AGCTHRESH2_STEP3_14 0x0E +#define RF_AGCTHRESH2_STEP3_15 0x0F + + +// RegAgcThresh3 +#define RF_AGCTHRESH3_STEP4_0 0x00 +#define RF_AGCTHRESH3_STEP4_1 0x10 +#define RF_AGCTHRESH3_STEP4_2 0x20 +#define RF_AGCTHRESH3_STEP4_3 0x30 +#define RF_AGCTHRESH3_STEP4_4 0x40 +#define RF_AGCTHRESH3_STEP4_5 0x50 +#define RF_AGCTHRESH3_STEP4_6 0x60 +#define RF_AGCTHRESH3_STEP4_7 0x70 +#define RF_AGCTHRESH3_STEP4_8 0x80 +#define RF_AGCTHRESH3_STEP4_9 0x90 // Default +#define RF_AGCTHRESH3_STEP4_10 0xA0 +#define RF_AGCTHRESH3_STEP4_11 0xB0 +#define RF_AGCTHRESH3_STEP4_12 0xC0 +#define RF_AGCTHRESH3_STEP4_13 0xD0 +#define RF_AGCTHRESH3_STEP4_14 0xE0 +#define RF_AGCTHRESH3_STEP4_15 0xF0 + +#define RF_AGCTHRESH3_STEP5_0 0x00 +#define RF_AGCTHRESH3_STEP5_1 0x01 +#define RF_AGCTHRESH3_STEP5_2 0x02 +#define RF_AGCTHRESH3_STEP5_3 0x03 +#define RF_AGCTHRESH3_STEP5_4 0x04 +#define RF_AGCTHRESH3_STEP5_5 0x05 +#define RF_AGCTHRESH3_STEP5_6 0x06 +#define RF_AGCTHRESH3_STEP5_7 0x07 +#define RF_AGCTHRES33_STEP5_8 0x08 +#define RF_AGCTHRESH3_STEP5_9 0x09 +#define RF_AGCTHRESH3_STEP5_10 0x0A +#define RF_AGCTHRESH3_STEP5_11 0x0B // Default +#define RF_AGCTHRESH3_STEP5_12 0x0C +#define RF_AGCTHRESH3_STEP5_13 0x0D +#define RF_AGCTHRESH3_STEP5_14 0x0E +#define RF_AGCTHRESH3_STEP5_15 0x0F + + +// RegLna +#define RF_LNA_ZIN_50 0x00 +#define RF_LNA_ZIN_200 0x80 // Default + +#define RF_LNA_LOWPOWER_OFF 0x00 // Default +#define RF_LNA_LOWPOWER_ON 0x40 + +#define RF_LNA_CURRENTGAIN 0x08 + +#define RF_LNA_GAINSELECT_AUTO 0x00 // Default +#define RF_LNA_GAINSELECT_MAX 0x01 +#define RF_LNA_GAINSELECT_MAXMINUS6 0x02 +#define RF_LNA_GAINSELECT_MAXMINUS12 0x03 +#define RF_LNA_GAINSELECT_MAXMINUS24 0x04 +#define RF_LNA_GAINSELECT_MAXMINUS36 0x05 +#define RF_LNA_GAINSELECT_MAXMINUS48 0x06 + + +// RegRxBw +#define RF_RXBW_DCCFREQ_000 0x00 +#define RF_RXBW_DCCFREQ_001 0x20 +#define RF_RXBW_DCCFREQ_010 0x40 // Default +#define RF_RXBW_DCCFREQ_011 0x60 +#define RF_RXBW_DCCFREQ_100 0x80 +#define RF_RXBW_DCCFREQ_101 0xA0 +#define RF_RXBW_DCCFREQ_110 0xC0 +#define RF_RXBW_DCCFREQ_111 0xE0 + +#define RF_RXBW_MANT_16 0x00 +#define RF_RXBW_MANT_20 0x08 +#define RF_RXBW_MANT_24 0x10 // Default + +#define RF_RXBW_EXP_0 0x00 +#define RF_RXBW_EXP_1 0x01 +#define RF_RXBW_EXP_2 0x02 +#define RF_RXBW_EXP_3 0x03 +#define RF_RXBW_EXP_4 0x04 +#define RF_RXBW_EXP_5 0x05 // Default +#define RF_RXBW_EXP_6 0x06 +#define RF_RXBW_EXP_7 0x07 + + +// RegAfcBw +#define RF_AFCBW_DCCFREQAFC_000 0x00 +#define RF_AFCBW_DCCFREQAFC_001 0x20 +#define RF_AFCBW_DCCFREQAFC_010 0x40 +#define RF_AFCBW_DCCFREQAFC_011 0x60 +#define RF_AFCBW_DCCFREQAFC_100 0x80 // Default +#define RF_AFCBW_DCCFREQAFC_101 0xA0 +#define RF_AFCBW_DCCFREQAFC_110 0xC0 +#define RF_AFCBW_DCCFREQAFC_111 0xE0 + +#define RF_AFCBW_MANTAFC_16 0x00 +#define RF_AFCBW_MANTAFC_20 0x08 // Default +#define RF_AFCBW_MANTAFC_24 0x10 + +#define RF_AFCBW_EXPAFC_0 0x00 +#define RF_AFCBW_EXPAFC_1 0x01 +#define RF_AFCBW_EXPAFC_2 0x02 +#define RF_AFCBW_EXPAFC_3 0x03 // Default +#define RF_AFCBW_EXPAFC_4 0x04 +#define RF_AFCBW_EXPAFC_5 0x05 +#define RF_AFCBW_EXPAFC_6 0x06 +#define RF_AFCBW_EXPAFC_7 0x07 + + +// RegOokPeak +#define RF_OOKPEAK_THRESHTYPE_FIXED 0x00 +#define RF_OOKPEAK_THRESHTYPE_PEAK 0x40 // Default +#define RF_OOKPEAK_THRESHTYPE_AVERAGE 0x80 + +#define RF_OOKPEAK_PEAKTHRESHSTEP_000 0x00 // Default +#define RF_OOKPEAK_PEAKTHRESHSTEP_001 0x08 +#define RF_OOKPEAK_PEAKTHRESHSTEP_010 0x10 +#define RF_OOKPEAK_PEAKTHRESHSTEP_011 0x18 +#define RF_OOKPEAK_PEAKTHRESHSTEP_100 0x20 +#define RF_OOKPEAK_PEAKTHRESHSTEP_101 0x28 +#define RF_OOKPEAK_PEAKTHRESHSTEP_110 0x30 +#define RF_OOKPEAK_PEAKTHRESHSTEP_111 0x38 + +#define RF_OOKPEAK_PEAKTHRESHDEC_000 0x00 // Default +#define RF_OOKPEAK_PEAKTHRESHDEC_001 0x01 +#define RF_OOKPEAK_PEAKTHRESHDEC_010 0x02 +#define RF_OOKPEAK_PEAKTHRESHDEC_011 0x03 +#define RF_OOKPEAK_PEAKTHRESHDEC_100 0x04 +#define RF_OOKPEAK_PEAKTHRESHDEC_101 0x05 +#define RF_OOKPEAK_PEAKTHRESHDEC_110 0x06 +#define RF_OOKPEAK_PEAKTHRESHDEC_111 0x07 + + +// RegOokAvg +#define RF_OOKAVG_AVERAGETHRESHFILT_00 0x00 +#define RF_OOKAVG_AVERAGETHRESHFILT_01 0x40 +#define RF_OOKAVG_AVERAGETHRESHFILT_10 0x80 // Default +#define RF_OOKAVG_AVERAGETHRESHFILT_11 0xC0 + + +// RegOokFix +#define RF_OOKFIX_FIXEDTHRESH_VALUE 0x06 // Default + + +// RegAfcFei +#define RF_AFCFEI_FEI_DONE 0x40 +#define RF_AFCFEI_FEI_START 0x20 +#define RF_AFCFEI_AFC_DONE 0x10 +#define RF_AFCFEI_AFCAUTOCLEAR_ON 0x08 +#define RF_AFCFEI_AFCAUTOCLEAR_OFF 0x00 // Default + +#define RF_AFCFEI_AFCAUTO_ON 0x04 +#define RF_AFCFEI_AFCAUTO_OFF 0x00 // Default + +#define RF_AFCFEI_AFC_CLEAR 0x02 +#define RF_AFCFEI_AFC_START 0x01 + +// RegRssiConfig +#define RF_RSSI_FASTRX_ON 0x08 +#define RF_RSSI_FASTRX_OFF 0x00 // Default +#define RF_RSSI_DONE 0x02 +#define RF_RSSI_START 0x01 + + +// RegDioMapping1 +#define RF_DIOMAPPING1_DIO0_00 0x00 // Default +#define RF_DIOMAPPING1_DIO0_01 0x40 +#define RF_DIOMAPPING1_DIO0_10 0x80 +#define RF_DIOMAPPING1_DIO0_11 0xC0 + +#define RF_DIOMAPPING1_DIO1_00 0x00 // Default +#define RF_DIOMAPPING1_DIO1_01 0x10 +#define RF_DIOMAPPING1_DIO1_10 0x20 +#define RF_DIOMAPPING1_DIO1_11 0x30 + +#define RF_DIOMAPPING1_DIO2_00 0x00 // Default +#define RF_DIOMAPPING1_DIO2_01 0x04 +#define RF_DIOMAPPING1_DIO2_10 0x08 +#define RF_DIOMAPPING1_DIO2_11 0x0C + +#define RF_DIOMAPPING1_DIO3_00 0x00 // Default +#define RF_DIOMAPPING1_DIO3_01 0x01 +#define RF_DIOMAPPING1_DIO3_10 0x02 +#define RF_DIOMAPPING1_DIO3_11 0x03 + + +// RegDioMapping2 +#define RF_DIOMAPPING2_DIO4_00 0x00 // Default +#define RF_DIOMAPPING2_DIO4_01 0x40 +#define RF_DIOMAPPING2_DIO4_10 0x80 +#define RF_DIOMAPPING2_DIO4_11 0xC0 + +#define RF_DIOMAPPING2_DIO5_00 0x00 // Default +#define RF_DIOMAPPING2_DIO5_01 0x10 +#define RF_DIOMAPPING2_DIO5_10 0x20 +#define RF_DIOMAPPING2_DIO5_11 0x30 + +#define RF_DIOMAPPING2_CLKOUT_32 0x00 +#define RF_DIOMAPPING2_CLKOUT_16 0x01 +#define RF_DIOMAPPING2_CLKOUT_8 0x02 +#define RF_DIOMAPPING2_CLKOUT_4 0x03 +#define RF_DIOMAPPING2_CLKOUT_2 0x04 +#define RF_DIOMAPPING2_CLKOUT_1 0x05 +#define RF_DIOMAPPING2_CLKOUT_RC 0x06 +#define RF_DIOMAPPING2_CLKOUT_OFF 0x07 // Default + + +// RegIrqFlags1 +#define RF_IRQFLAGS1_MODEREADY 0x80 +#define RF_IRQFLAGS1_RXREADY 0x40 +#define RF_IRQFLAGS1_TXREADY 0x20 +#define RF_IRQFLAGS1_PLLLOCK 0x10 +#define RF_IRQFLAGS1_RSSI 0x08 +#define RF_IRQFLAGS1_TIMEOUT 0x04 +#define RF_IRQFLAGS1_AUTOMODE 0x02 +#define RF_IRQFLAGS1_SYNCADDRESSMATCH 0x01 + +// RegIrqFlags2 +#define RF_IRQFLAGS2_FIFOFULL 0x80 +#define RF_IRQFLAGS2_FIFONOTEMPTY 0x40 +#define RF_IRQFLAGS2_FIFOLEVEL 0x20 +#define RF_IRQFLAGS2_FIFOOVERRUN 0x10 +#define RF_IRQFLAGS2_PACKETSENT 0x08 +#define RF_IRQFLAGS2_PAYLOADREADY 0x04 +#define RF_IRQFLAGS2_CRCOK 0x02 +#define RF_IRQFLAGS2_LOWBAT 0x01 + +// RegRssiThresh +#define RF_RSSITHRESH_VALUE 0xE4 // Default + +// RegRxTimeout1 +#define RF_RXTIMEOUT1_RXSTART_VALUE 0x00 // Default + +// RegRxTimeout2 +#define RF_RXTIMEOUT2_RSSITHRESH_VALUE 0x00 // Default + +// RegPreamble +#define RF_PREAMBLESIZE_MSB_VALUE 0x00 // Default +#define RF_PREAMBLESIZE_LSB_VALUE 0x03 // Default + + +// RegSyncConfig +#define RF_SYNC_ON 0x80 // Default +#define RF_SYNC_OFF 0x00 + +#define RF_SYNC_FIFOFILL_AUTO 0x00 // Default -- when sync interrupt occurs +#define RF_SYNC_FIFOFILL_MANUAL 0x40 + +#define RF_SYNC_SIZE_1 0x00 +#define RF_SYNC_SIZE_2 0x08 +#define RF_SYNC_SIZE_3 0x10 +#define RF_SYNC_SIZE_4 0x18 // Default +#define RF_SYNC_SIZE_5 0x20 +#define RF_SYNC_SIZE_6 0x28 +#define RF_SYNC_SIZE_7 0x30 +#define RF_SYNC_SIZE_8 0x38 + +#define RF_SYNC_TOL_0 0x00 // Default +#define RF_SYNC_TOL_1 0x01 +#define RF_SYNC_TOL_2 0x02 +#define RF_SYNC_TOL_3 0x03 +#define RF_SYNC_TOL_4 0x04 +#define RF_SYNC_TOL_5 0x05 +#define RF_SYNC_TOL_6 0x06 +#define RF_SYNC_TOL_7 0x07 + + +// RegSyncValue1-8 +#define RF_SYNC_BYTE1_VALUE 0x00 // Default +#define RF_SYNC_BYTE2_VALUE 0x00 // Default +#define RF_SYNC_BYTE3_VALUE 0x00 // Default +#define RF_SYNC_BYTE4_VALUE 0x00 // Default +#define RF_SYNC_BYTE5_VALUE 0x00 // Default +#define RF_SYNC_BYTE6_VALUE 0x00 // Default +#define RF_SYNC_BYTE7_VALUE 0x00 // Default +#define RF_SYNC_BYTE8_VALUE 0x00 // Default + + +// RegPacketConfig1 +#define RF_PACKET1_FORMAT_FIXED 0x00 // Default +#define RF_PACKET1_FORMAT_VARIABLE 0x80 + +#define RF_PACKET1_DCFREE_OFF 0x00 // Default +#define RF_PACKET1_DCFREE_MANCHESTER 0x20 +#define RF_PACKET1_DCFREE_WHITENING 0x40 + +#define RF_PACKET1_CRC_ON 0x10 // Default +#define RF_PACKET1_CRC_OFF 0x00 + +#define RF_PACKET1_CRCAUTOCLEAR_ON 0x00 // Default +#define RF_PACKET1_CRCAUTOCLEAR_OFF 0x08 + +#define RF_PACKET1_ADRSFILTERING_OFF 0x00 // Default +#define RF_PACKET1_ADRSFILTERING_NODE 0x02 +#define RF_PACKET1_ADRSFILTERING_NODEBROADCAST 0x04 + + +// RegPayloadLength +#define RF_PAYLOADLENGTH_VALUE 0x40 // Default + +// RegBroadcastAdrs +#define RF_BROADCASTADDRESS_VALUE 0x00 + + +// RegAutoModes +#define RF_AUTOMODES_ENTER_OFF 0x00 // Default +#define RF_AUTOMODES_ENTER_FIFONOTEMPTY 0x20 +#define RF_AUTOMODES_ENTER_FIFOLEVEL 0x40 +#define RF_AUTOMODES_ENTER_CRCOK 0x60 +#define RF_AUTOMODES_ENTER_PAYLOADREADY 0x80 +#define RF_AUTOMODES_ENTER_SYNCADRSMATCH 0xA0 +#define RF_AUTOMODES_ENTER_PACKETSENT 0xC0 +#define RF_AUTOMODES_ENTER_FIFOEMPTY 0xE0 + +#define RF_AUTOMODES_EXIT_OFF 0x00 // Default +#define RF_AUTOMODES_EXIT_FIFOEMPTY 0x04 +#define RF_AUTOMODES_EXIT_FIFOLEVEL 0x08 +#define RF_AUTOMODES_EXIT_CRCOK 0x0C +#define RF_AUTOMODES_EXIT_PAYLOADREADY 0x10 +#define RF_AUTOMODES_EXIT_SYNCADRSMATCH 0x14 +#define RF_AUTOMODES_EXIT_PACKETSENT 0x18 +#define RF_AUTOMODES_EXIT_RXTIMEOUT 0x1C + +#define RF_AUTOMODES_INTERMEDIATE_SLEEP 0x00 // Default +#define RF_AUTOMODES_INTERMEDIATE_STANDBY 0x01 +#define RF_AUTOMODES_INTERMEDIATE_RECEIVER 0x02 +#define RF_AUTOMODES_INTERMEDIATE_TRANSMITTER 0x03 + + +// RegFifoThresh +#define RF_FIFOTHRESH_TXSTART_FIFOTHRESH 0x00 +#define RF_FIFOTHRESH_TXSTART_FIFONOTEMPTY 0x80 // Default + +#define RF_FIFOTHRESH_VALUE 0x0F // Default + + +// RegPacketConfig2 +#define RF_PACKET2_RXRESTARTDELAY_1BIT 0x00 // Default +#define RF_PACKET2_RXRESTARTDELAY_2BITS 0x10 +#define RF_PACKET2_RXRESTARTDELAY_4BITS 0x20 +#define RF_PACKET2_RXRESTARTDELAY_8BITS 0x30 +#define RF_PACKET2_RXRESTARTDELAY_16BITS 0x40 +#define RF_PACKET2_RXRESTARTDELAY_32BITS 0x50 +#define RF_PACKET2_RXRESTARTDELAY_64BITS 0x60 +#define RF_PACKET2_RXRESTARTDELAY_128BITS 0x70 +#define RF_PACKET2_RXRESTARTDELAY_256BITS 0x80 +#define RF_PACKET2_RXRESTARTDELAY_512BITS 0x90 +#define RF_PACKET2_RXRESTARTDELAY_1024BITS 0xA0 +#define RF_PACKET2_RXRESTARTDELAY_2048BITS 0xB0 +#define RF_PACKET2_RXRESTARTDELAY_NONE 0xC0 +#define RF_PACKET2_RXRESTART 0x04 + +#define RF_PACKET2_AUTORXRESTART_ON 0x02 // Default +#define RF_PACKET2_AUTORXRESTART_OFF 0x00 + +#define RF_PACKET2_AES_ON 0x01 +#define RF_PACKET2_AES_OFF 0x00 // Default + + +// RegAesKey1-16 +#define RF_AESKEY1_VALUE 0x00 // Default +#define RF_AESKEY2_VALUE 0x00 // Default +#define RF_AESKEY3_VALUE 0x00 // Default +#define RF_AESKEY4_VALUE 0x00 // Default +#define RF_AESKEY5_VALUE 0x00 // Default +#define RF_AESKEY6_VALUE 0x00 // Default +#define RF_AESKEY7_VALUE 0x00 // Default +#define RF_AESKEY8_VALUE 0x00 // Default +#define RF_AESKEY9_VALUE 0x00 // Default +#define RF_AESKEY10_VALUE 0x00 // Default +#define RF_AESKEY11_VALUE 0x00 // Default +#define RF_AESKEY12_VALUE 0x00 // Default +#define RF_AESKEY13_VALUE 0x00 // Default +#define RF_AESKEY14_VALUE 0x00 // Default +#define RF_AESKEY15_VALUE 0x00 // Default +#define RF_AESKEY16_VALUE 0x00 // Default + + +// RegTemp1 +#define RF_TEMP1_MEAS_START 0x08 +#define RF_TEMP1_MEAS_RUNNING 0x04 +#define RF_TEMP1_ADCLOWPOWER_ON 0x01 // Default +#define RF_TEMP1_ADCLOWPOWER_OFF 0x00 + +// RegTestDagc 0x6F: demodulator config and IO mode config +#define RF_DAGC_NORMAL 0x00 // Reset value +#define RF_DAGC_IMPROVED_LOWBETA1 0x20 // +#define RF_DAGC_IMPROVED_LOWBETA0 0x30 // Recommended default + From f143fcd7a2d2e6f093cb11908ef72fc439a05987 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 3 Nov 2014 20:08:56 +0100 Subject: [PATCH 024/137] Moved RFM69 library to utility --- libraries/MySensors/MyDriverRF69.cpp | 1 - libraries/MySensors/MyDriverRF69.h | 4 ++-- libraries/MySensors/{ => utility}/RFM69.cpp | 6 +++--- libraries/MySensors/{ => utility}/RFM69.h | 0 libraries/MySensors/{ => utility}/RFM69registers.h | 0 5 files changed, 5 insertions(+), 6 deletions(-) rename libraries/MySensors/{ => utility}/RFM69.cpp (99%) rename libraries/MySensors/{ => utility}/RFM69.h (100%) rename libraries/MySensors/{ => utility}/RFM69registers.h (100%) diff --git a/libraries/MySensors/MyDriverRF69.cpp b/libraries/MySensors/MyDriverRF69.cpp index 126e364..2363da7 100644 --- a/libraries/MySensors/MyDriverRF69.cpp +++ b/libraries/MySensors/MyDriverRF69.cpp @@ -1,4 +1,3 @@ -#include #include "MyDriver.h" #include "MyDriverRF69.h" diff --git a/libraries/MySensors/MyDriverRF69.h b/libraries/MySensors/MyDriverRF69.h index 4c53786..6b14772 100644 --- a/libraries/MySensors/MyDriverRF69.h +++ b/libraries/MySensors/MyDriverRF69.h @@ -4,7 +4,7 @@ #include "MyConfig.h" #include "MyDriver.h" #include -#include "RFM69.h" +#include "utility/RFM69.h" #include #define NODEID 2 //unique for each node on same network @@ -41,4 +41,4 @@ private: uint8_t _address; }; -#endif \ No newline at end of file +#endif diff --git a/libraries/MySensors/RFM69.cpp b/libraries/MySensors/utility/RFM69.cpp similarity index 99% rename from libraries/MySensors/RFM69.cpp rename to libraries/MySensors/utility/RFM69.cpp index 8b0305f..24bb2d3 100644 --- a/libraries/MySensors/RFM69.cpp +++ b/libraries/MySensors/utility/RFM69.cpp @@ -29,8 +29,8 @@ // Please maintain this license information along with authorship // and copyright notices in any redistribution of this code // ********************************************************************************** -#include -#include +#include "RFM69.h" +#include "RFM69registers.h" #include volatile byte RFM69::DATA[RF69_MAX_DATA_LEN]; @@ -461,4 +461,4 @@ void RFM69::rcCalibration() { writeReg(REG_OSC1, RF_OSC1_RCCAL_START); while ((readReg(REG_OSC1) & RF_OSC1_RCCAL_DONE) == 0x00); -} \ No newline at end of file +} diff --git a/libraries/MySensors/RFM69.h b/libraries/MySensors/utility/RFM69.h similarity index 100% rename from libraries/MySensors/RFM69.h rename to libraries/MySensors/utility/RFM69.h diff --git a/libraries/MySensors/RFM69registers.h b/libraries/MySensors/utility/RFM69registers.h similarity index 100% rename from libraries/MySensors/RFM69registers.h rename to libraries/MySensors/utility/RFM69registers.h From 9fd41b403064dd8c0d1c06f536ec8b1d5bb4229d Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 10 Jan 2015 12:30:10 +0100 Subject: [PATCH 025/137] Added sha204 library Taken from the sha204_library folder in https://github.com/jimblom/sha204-Breakout Commit 8e1ac05ef987b1869605ad067db2bdbaec1c109f ATSHA204 is a crypto cirquit from Atmel that enables SHA256-based MAC and HMAC calculations as well as secure key storage and random number generation. This can be used to sign messages passed between sensor nodes and prevent both man-in-the-middle and replay attacking. --- .../atsha204_simple_example.ino | 103 +++ .../sha204_includes/sha204_lib_return_codes.h | 48 ++ libraries/sha204/sha204_library.cpp | 809 ++++++++++++++++++ libraries/sha204/sha204_library.h | 320 +++++++ 4 files changed, 1280 insertions(+) create mode 100644 libraries/sha204/examples/atsha204_simple_example/atsha204_simple_example.ino create mode 100644 libraries/sha204/sha204_includes/sha204_lib_return_codes.h create mode 100644 libraries/sha204/sha204_library.cpp create mode 100644 libraries/sha204/sha204_library.h diff --git a/libraries/sha204/examples/atsha204_simple_example/atsha204_simple_example.ino b/libraries/sha204/examples/atsha204_simple_example/atsha204_simple_example.ino new file mode 100644 index 0000000..b55ce49 --- /dev/null +++ b/libraries/sha204/examples/atsha204_simple_example/atsha204_simple_example.ino @@ -0,0 +1,103 @@ +/* ATSHA204 Library Simple Example + by: Jim Lindblom + SparkFun Electronics + date: November 8, 2012 + + This code shows how to wake up and verify that an SHA204 is + connected and operational. And how to obtain an SHA204's unique serial + number, and send it a MAC challenge. + + The ATSHA204's SDA pin can be connected to any of the Arduino's digital pins. + When constructing your atsha204Class, pass the constructor the pin you want to use. + In this example we'll attach SDA to pin 7. + + The ATSHA204 can be powered between 3.3V and 5V. +*/ +#include + +const int sha204Pin = 7; + +atsha204Class sha204(sha204Pin); + +void setup() +{ + Serial.begin(9600); + Serial.println("Sending a Wakup Command. Response should be:\r\n4 11 33 43:"); + Serial.println("Response is:"); + wakeupExample(); + Serial.println(); + Serial.println("Asking the SHA204's serial number. Response should be:"); + Serial.println("1 23 x x x x x x x EE"); + Serial.println("Response is:"); + serialNumberExample(); + Serial.println(); + Serial.println("Sending a MAC Challenge. Response should be:"); + Serial.println("23 6 67 0 4F 28 4D 6E 98 62 4 F4 60 A3 E8 75 8A 59 85 A6 79 96 C4 8A 88 46 43 4E B3 DB 58 A4 FB E5 73"); + Serial.println("Response is:"); + macChallengeExample(); +} + +void loop() +{ +} + +byte wakeupExample() +{ + uint8_t response[SHA204_RSP_SIZE_MIN]; + byte returnValue; + + returnValue = sha204.sha204c_wakeup(&response[0]); + for (int i=0; i // data type definitions + +/** \todo Use same values for same meanings for SHA204 and AES132. + * */ + +#define SHA204_SUCCESS ((uint8_t) 0x00) //!< Function succeeded. +#define SHA204_PARSE_ERROR ((uint8_t) 0xD2) //!< response status byte indicates parsing error +#define SHA204_CMD_FAIL ((uint8_t) 0xD3) //!< response status byte indicates command execution error +#define SHA204_STATUS_CRC ((uint8_t) 0xD4) //!< response status byte indicates CRC error +#define SHA204_STATUS_UNKNOWN ((uint8_t) 0xD5) //!< response status byte is unknown +#define SHA204_FUNC_FAIL ((uint8_t) 0xE0) //!< Function could not execute due to incorrect condition / state. +#define SHA204_GEN_FAIL ((uint8_t) 0xE1) //!< unspecified error +#define SHA204_BAD_PARAM ((uint8_t) 0xE2) //!< bad argument (out of range, null pointer, etc.) +#define SHA204_INVALID_ID ((uint8_t) 0xE3) //!< invalid device id, id not set +#define SHA204_INVALID_SIZE ((uint8_t) 0xE4) //!< Count value is out of range or greater than buffer size. +#define SHA204_BAD_CRC ((uint8_t) 0xE5) //!< incorrect CRC received +#define SHA204_RX_FAIL ((uint8_t) 0xE6) //!< Timed out while waiting for response. Number of bytes received is > 0. +#define SHA204_RX_NO_RESPONSE ((uint8_t) 0xE7) //!< Not an error while the Command layer is polling for a command response. +#define SHA204_RESYNC_WITH_WAKEUP ((uint8_t) 0xE8) //!< re-synchronization succeeded, but only after generating a Wake-up + +#define SHA204_COMM_FAIL ((uint8_t) 0xF0) //!< Communication with device failed. Same as in hardware dependent modules. +#define SHA204_TIMEOUT ((uint8_t) 0xF1) //!< Timed out while waiting for response. Number of bytes received is 0. + +#endif diff --git a/libraries/sha204/sha204_library.cpp b/libraries/sha204/sha204_library.cpp new file mode 100644 index 0000000..075242f --- /dev/null +++ b/libraries/sha204/sha204_library.cpp @@ -0,0 +1,809 @@ +#include "Arduino.h" +#include "sha204_library.h" +#include "sha204_includes/sha204_lib_return_codes.h" + + +// atsha204Class Constructor +// Feed this function the Arduino-ized pin number you want to assign to the ATSHA204's SDA pin +// This will find the DDRX, PORTX, and PINX registrs it'll need to point to to control that pin +// As well as the bit value for each of those registers +atsha204Class::atsha204Class(uint8_t pin) +{ + device_pin = digitalPinToBitMask(pin); // Find the bit value of the pin + uint8_t port = digitalPinToPort(pin); // temoporarily used to get the next three registers + + // Point to data direction register port of pin + device_port_DDR = portModeRegister(port); + // Point to output register of pin + device_port_OUT = portOutputRegister(port); + // Point to input register of pin + device_port_IN = portInputRegister(port); +} + +/* Puts a the ATSHA204's unique, 4-byte serial number in the response array + returns an SHA204 Return code */ +uint8_t atsha204Class::getSerialNumber(uint8_t * response) +{ + uint8_t readCommand[READ_COUNT]; + uint8_t readResponse[READ_4_RSP_SIZE]; + + /* read from bytes 0->3 of config zone */ + uint8_t returnCode = sha204m_read(readCommand, readResponse, SHA204_ZONE_CONFIG, ADDRESS_SN03); + if (!returnCode) // should return 0 if successful + { + for (int i=0; i<4; i++) // store bytes 0-3 into respones array + response[i] = readResponse[SHA204_BUFFER_POS_DATA+i]; + + /* read from bytes 8->11 of config zone */ + returnCode = sha204m_read(readCommand, readResponse, SHA204_ZONE_CONFIG, ADDRESS_SN47); + + for (int i=4; i<8; i++) // store bytes 4-7 of SN into response array + response[i] = readResponse[SHA204_BUFFER_POS_DATA+(i-4)]; + + if (!returnCode) + { /* Finally if last two reads were successful, read byte 8 of the SN */ + returnCode = sha204m_read(readCommand, readResponse, SHA204_ZONE_CONFIG, ADDRESS_SN8); + response[8] = readResponse[SHA204_BUFFER_POS_DATA]; // Byte 8 of SN should always be 0xEE + } + } + + return returnCode; +} + +/* SWI bit bang functions */ + +void atsha204Class::swi_set_signal_pin(uint8_t is_high) +{ + *device_port_DDR |= device_pin; + + if (is_high) + *device_port_OUT |= device_pin; + else + *device_port_OUT &= ~device_pin; +} + +uint8_t atsha204Class::swi_send_bytes(uint8_t count, uint8_t *buffer) +{ + uint8_t i, bit_mask; + + // Disable interrupts while sending. + noInterrupts(); //swi_disable_interrupts(); + + // Set signal pin as output. + *device_port_OUT |= device_pin; + *device_port_DDR |= device_pin; + + // Wait turn around time. + delayMicroseconds(RX_TX_DELAY); //RX_TX_DELAY; + + for (i = 0; i < count; i++) + { + for (bit_mask = 1; bit_mask > 0; bit_mask <<= 1) + { + if (bit_mask & buffer[i]) + { + *device_port_OUT &= ~device_pin; + delayMicroseconds(BIT_DELAY); //BIT_DELAY_1; + *device_port_OUT |= device_pin; + delayMicroseconds(7*BIT_DELAY); //BIT_DELAY_7; + } + else + { + // Send a zero bit. + *device_port_OUT &= ~device_pin; + delayMicroseconds(BIT_DELAY); //BIT_DELAY_1; + *device_port_OUT |= device_pin; + delayMicroseconds(BIT_DELAY); //BIT_DELAY_1; + *device_port_OUT &= ~device_pin; + delayMicroseconds(BIT_DELAY); //BIT_DELAY_1; + *device_port_OUT |= device_pin; + delayMicroseconds(5*BIT_DELAY); //BIT_DELAY_5; + } + } + } + interrupts(); //swi_enable_interrupts(); + return SWI_FUNCTION_RETCODE_SUCCESS; +} + +uint8_t atsha204Class::swi_send_byte(uint8_t value) +{ + return swi_send_bytes(1, &value); +} + +uint8_t atsha204Class::swi_receive_bytes(uint8_t count, uint8_t *buffer) +{ + uint8_t status = SWI_FUNCTION_RETCODE_SUCCESS; + uint8_t i; + uint8_t bit_mask; + uint8_t pulse_count; + uint8_t timeout_count; + + // Disable interrupts while receiving. + noInterrupts(); //swi_disable_interrupts(); + + // Configure signal pin as input. + *device_port_DDR &= ~device_pin; + + // Receive bits and store in buffer. + for (i = 0; i < count; i++) + { + for (bit_mask = 1; bit_mask > 0; bit_mask <<= 1) + { + pulse_count = 0; + + // Make sure that the variable below is big enough. + // Change it to uint16_t if 255 is too small, but be aware that + // the loop resolution decreases on an 8-bit controller in that case. + timeout_count = START_PULSE_TIME_OUT; + + // Detect start bit. + while (--timeout_count > 0) + { + // Wait for falling edge. + if ((*device_port_IN & device_pin) == 0) + break; + } + + if (timeout_count == 0) + { + status = SWI_FUNCTION_RETCODE_TIMEOUT; + break; + } + + do + { + // Wait for rising edge. + if ((*device_port_IN & device_pin) != 0) + { + // For an Atmel microcontroller this might be faster than "pulse_count++". + pulse_count = 1; + break; + } + } while (--timeout_count > 0); + + if (pulse_count == 0) + { + status = SWI_FUNCTION_RETCODE_TIMEOUT; + break; + } + + // Trying to measure the time of start bit and calculating the timeout + // for zero bit detection is not accurate enough for an 8 MHz 8-bit CPU. + // So let's just wait the maximum time for the falling edge of a zero bit + // to arrive after we have detected the rising edge of the start bit. + timeout_count = ZERO_PULSE_TIME_OUT; + + // Detect possible edge indicating zero bit. + do + { + if ((*device_port_IN & device_pin) == 0) + { + // For an Atmel microcontroller this might be faster than "pulse_count++". + pulse_count = 2; + break; + } + } while (--timeout_count > 0); + + // Wait for rising edge of zero pulse before returning. Otherwise we might interpret + // its rising edge as the next start pulse. + if (pulse_count == 2) + { + do + { + if ((*device_port_IN & device_pin) != 0) + break; + } while (timeout_count-- > 0); + } + + // Update byte at current buffer index. + else + buffer[i] |= bit_mask; // received "one" bit + } + + if (status != SWI_FUNCTION_RETCODE_SUCCESS) + break; + } + interrupts(); //swi_enable_interrupts(); + + if (status == SWI_FUNCTION_RETCODE_TIMEOUT) + { + if (i > 0) + // Indicate that we timed out after having received at least one byte. + status = SWI_FUNCTION_RETCODE_RX_FAIL; + } + return status; +} + +/* Physical functions */ + +uint8_t atsha204Class::sha204p_wakeup() +{ + swi_set_signal_pin(0); + delayMicroseconds(10*SHA204_WAKEUP_PULSE_WIDTH); + swi_set_signal_pin(1); + delay(SHA204_WAKEUP_DELAY); + + return SHA204_SUCCESS; +} + +uint8_t atsha204Class::sha204p_sleep() +{ + return swi_send_byte(SHA204_SWI_FLAG_SLEEP); +} + +uint8_t atsha204Class::sha204p_resync(uint8_t size, uint8_t *response) +{ + delay(SHA204_SYNC_TIMEOUT); + return sha204p_receive_response(size, response); +} + +uint8_t atsha204Class::sha204p_receive_response(uint8_t size, uint8_t *response) +{ + uint8_t count_byte; + uint8_t i; + uint8_t ret_code; + + for (i = 0; i < size; i++) + response[i] = 0; + + (void) swi_send_byte(SHA204_SWI_FLAG_TX); + + ret_code = swi_receive_bytes(size, response); + if (ret_code == SWI_FUNCTION_RETCODE_SUCCESS || ret_code == SWI_FUNCTION_RETCODE_RX_FAIL) + { + count_byte = response[SHA204_BUFFER_POS_COUNT]; + if ((count_byte < SHA204_RSP_SIZE_MIN) || (count_byte > size)) + return SHA204_INVALID_SIZE; + + return SHA204_SUCCESS; + } + + // Translate error so that the Communication layer + // can distinguish between a real error or the + // device being busy executing a command. + if (ret_code == SWI_FUNCTION_RETCODE_TIMEOUT) + return SHA204_RX_NO_RESPONSE; + else + return SHA204_RX_FAIL; +} + +uint8_t atsha204Class::sha204p_send_command(uint8_t count, uint8_t * command) +{ + uint8_t ret_code = swi_send_byte(SHA204_SWI_FLAG_CMD); + if (ret_code != SWI_FUNCTION_RETCODE_SUCCESS) + return SHA204_COMM_FAIL; + + return swi_send_bytes(count, command); +} + +/* Communication functions */ + +uint8_t atsha204Class::sha204c_wakeup(uint8_t *response) +{ + uint8_t ret_code = sha204p_wakeup(); + if (ret_code != SHA204_SUCCESS) + return ret_code; + + ret_code = sha204p_receive_response(SHA204_RSP_SIZE_MIN, response); + if (ret_code != SHA204_SUCCESS) + return ret_code; + + // Verify status response. + if (response[SHA204_BUFFER_POS_COUNT] != SHA204_RSP_SIZE_MIN) + ret_code = SHA204_INVALID_SIZE; + else if (response[SHA204_BUFFER_POS_STATUS] != SHA204_STATUS_BYTE_WAKEUP) + ret_code = SHA204_COMM_FAIL; + else + { + if ((response[SHA204_RSP_SIZE_MIN - SHA204_CRC_SIZE] != 0x33) + || (response[SHA204_RSP_SIZE_MIN + 1 - SHA204_CRC_SIZE] != 0x43)) + ret_code = SHA204_BAD_CRC; + } + if (ret_code != SHA204_SUCCESS) + delay(SHA204_COMMAND_EXEC_MAX); + + return ret_code; +} + +uint8_t atsha204Class::sha204c_resync(uint8_t size, uint8_t *response) +{ + // Try to re-synchronize without sending a Wake token + // (step 1 of the re-synchronization process). + uint8_t ret_code = sha204p_resync(size, response); + if (ret_code == SHA204_SUCCESS) + return ret_code; + + // We lost communication. Send a Wake pulse and try + // to receive a response (steps 2 and 3 of the + // re-synchronization process). + (void) sha204p_sleep(); + ret_code = sha204c_wakeup(response); + + // Translate a return value of success into one + // that indicates that the device had to be woken up + // and might have lost its TempKey. + return (ret_code == SHA204_SUCCESS ? SHA204_RESYNC_WITH_WAKEUP : ret_code); +} + +uint8_t atsha204Class::sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer, uint8_t execution_delay, uint8_t execution_timeout) +{ + uint8_t ret_code = SHA204_FUNC_FAIL; + uint8_t ret_code_resync; + uint8_t n_retries_send; + uint8_t n_retries_receive; + uint8_t i; + uint8_t status_byte; + uint8_t count = tx_buffer[SHA204_BUFFER_POS_COUNT]; + uint8_t count_minus_crc = count - SHA204_CRC_SIZE; + uint16_t execution_timeout_us = (uint16_t) (execution_timeout * 1000) + SHA204_RESPONSE_TIMEOUT; + volatile uint16_t timeout_countdown; + + // Append CRC. + sha204c_calculate_crc(count_minus_crc, tx_buffer, tx_buffer + count_minus_crc); + + // Retry loop for sending a command and receiving a response. + n_retries_send = SHA204_RETRY_COUNT + 1; + + while ((n_retries_send-- > 0) && (ret_code != SHA204_SUCCESS)) + { + // Send command. + ret_code = sha204p_send_command(count, tx_buffer); + if (ret_code != SHA204_SUCCESS) + { + if (sha204c_resync(rx_size, rx_buffer) == SHA204_RX_NO_RESPONSE) + return ret_code; // The device seems to be dead in the water. + else + continue; + } + + // Wait minimum command execution time and then start polling for a response. + delay(execution_delay); + + // Retry loop for receiving a response. + n_retries_receive = SHA204_RETRY_COUNT + 1; + while (n_retries_receive-- > 0) + { + // Reset response buffer. + for (i = 0; i < rx_size; i++) + rx_buffer[i] = 0; + + // Poll for response. + timeout_countdown = execution_timeout_us; + do + { + ret_code = sha204p_receive_response(rx_size, rx_buffer); + timeout_countdown -= SHA204_RESPONSE_TIMEOUT; + } + while ((timeout_countdown > SHA204_RESPONSE_TIMEOUT) && (ret_code == SHA204_RX_NO_RESPONSE)); + + if (ret_code == SHA204_RX_NO_RESPONSE) + { + // We did not receive a response. Re-synchronize and send command again. + if (sha204c_resync(rx_size, rx_buffer) == SHA204_RX_NO_RESPONSE) + // The device seems to be dead in the water. + return ret_code; + else + break; + } + + // Check whether we received a valid response. + if (ret_code == SHA204_INVALID_SIZE) + { + // We see 0xFF for the count when communication got out of sync. + ret_code_resync = sha204c_resync(rx_size, rx_buffer); + if (ret_code_resync == SHA204_SUCCESS) + // We did not have to wake up the device. Try receiving response again. + continue; + if (ret_code_resync == SHA204_RESYNC_WITH_WAKEUP) + // We could re-synchronize, but only after waking up the device. + // Re-send command. + break; + else + // We failed to re-synchronize. + return ret_code; + } + + // We received a response of valid size. + // Check the consistency of the response. + ret_code = sha204c_check_crc(rx_buffer); + if (ret_code == SHA204_SUCCESS) + { + // Received valid response. + if (rx_buffer[SHA204_BUFFER_POS_COUNT] > SHA204_RSP_SIZE_MIN) + // Received non-status response. We are done. + return ret_code; + + // Received status response. + status_byte = rx_buffer[SHA204_BUFFER_POS_STATUS]; + + // Translate the three possible device status error codes + // into library return codes. + if (status_byte == SHA204_STATUS_BYTE_PARSE) + return SHA204_PARSE_ERROR; + if (status_byte == SHA204_STATUS_BYTE_EXEC) + return SHA204_CMD_FAIL; + if (status_byte == SHA204_STATUS_BYTE_COMM) + { + // In case of the device status byte indicating a communication + // error this function exits the retry loop for receiving a response + // and enters the overall retry loop + // (send command / receive response). + ret_code = SHA204_STATUS_CRC; + break; + } + + // Received status response from CheckMAC, DeriveKey, GenDig, + // Lock, Nonce, Pause, UpdateExtra, or Write command. + return ret_code; + } + + else + { + // Received response with incorrect CRC. + ret_code_resync = sha204c_resync(rx_size, rx_buffer); + if (ret_code_resync == SHA204_SUCCESS) + // We did not have to wake up the device. Try receiving response again. + continue; + if (ret_code_resync == SHA204_RESYNC_WITH_WAKEUP) + // We could re-synchronize, but only after waking up the device. + // Re-send command. + break; + else + // We failed to re-synchronize. + return ret_code; + } // block end of check response consistency + + } // block end of receive retry loop + + } // block end of send and receive retry loop + + return ret_code; +} + + +/* Marshaling functions */ + +uint8_t atsha204Class::sha204m_random(uint8_t * tx_buffer, uint8_t * rx_buffer, uint8_t mode) +{ + if (!tx_buffer || !rx_buffer || (mode > RANDOM_NO_SEED_UPDATE)) + return SHA204_BAD_PARAM; + + tx_buffer[SHA204_COUNT_IDX] = RANDOM_COUNT; + tx_buffer[SHA204_OPCODE_IDX] = SHA204_RANDOM; + tx_buffer[RANDOM_MODE_IDX] = mode & RANDOM_SEED_UPDATE; + + tx_buffer[RANDOM_PARAM2_IDX] = + tx_buffer[RANDOM_PARAM2_IDX + 1] = 0; + + return sha204c_send_and_receive(&tx_buffer[0], RANDOM_RSP_SIZE, &rx_buffer[0], RANDOM_DELAY, RANDOM_EXEC_MAX - RANDOM_DELAY); +} + +uint8_t atsha204Class::sha204m_dev_rev(uint8_t *tx_buffer, uint8_t *rx_buffer) +{ + if (!tx_buffer || !rx_buffer) + return SHA204_BAD_PARAM; + + tx_buffer[SHA204_COUNT_IDX] = DEVREV_COUNT; + tx_buffer[SHA204_OPCODE_IDX] = SHA204_DEVREV; + + // Parameters are 0. + tx_buffer[DEVREV_PARAM1_IDX] = + tx_buffer[DEVREV_PARAM2_IDX] = + tx_buffer[DEVREV_PARAM2_IDX + 1] = 0; + + return sha204c_send_and_receive(&tx_buffer[0], DEVREV_RSP_SIZE, &rx_buffer[0], + DEVREV_DELAY, DEVREV_EXEC_MAX - DEVREV_DELAY); +} + +uint8_t atsha204Class::sha204m_read(uint8_t *tx_buffer, uint8_t *rx_buffer, uint8_t zone, uint16_t address) +{ + uint8_t rx_size; + + if (!tx_buffer || !rx_buffer || ((zone & ~READ_ZONE_MASK) != 0) + || ((zone & READ_ZONE_MODE_32_BYTES) && (zone == SHA204_ZONE_OTP))) + return SHA204_BAD_PARAM; + + address >>= 2; + if ((zone & SHA204_ZONE_MASK) == SHA204_ZONE_CONFIG) + { + if (address > SHA204_ADDRESS_MASK_CONFIG) + return SHA204_BAD_PARAM; + } + else if ((zone & SHA204_ZONE_MASK) == SHA204_ZONE_OTP) + { + if (address > SHA204_ADDRESS_MASK_OTP) + return SHA204_BAD_PARAM; + } + else if ((zone & SHA204_ZONE_MASK) == SHA204_ZONE_DATA) + { + if (address > SHA204_ADDRESS_MASK) + return SHA204_BAD_PARAM; + } + + tx_buffer[SHA204_COUNT_IDX] = READ_COUNT; + tx_buffer[SHA204_OPCODE_IDX] = SHA204_READ; + tx_buffer[READ_ZONE_IDX] = zone; + tx_buffer[READ_ADDR_IDX] = (uint8_t) (address & SHA204_ADDRESS_MASK); + tx_buffer[READ_ADDR_IDX + 1] = 0; + + rx_size = (zone & SHA204_ZONE_COUNT_FLAG) ? READ_32_RSP_SIZE : READ_4_RSP_SIZE; + + return sha204c_send_and_receive(&tx_buffer[0], rx_size, &rx_buffer[0], READ_DELAY, READ_EXEC_MAX - READ_DELAY); +} + +uint8_t atsha204Class::sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t param2, + uint8_t datalen1, uint8_t *data1, uint8_t datalen2, uint8_t *data2, uint8_t datalen3, uint8_t *data3, + uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer) +{ + uint8_t poll_delay, poll_timeout, response_size; + uint8_t *p_buffer; + uint8_t len; + + uint8_t ret_code = sha204m_check_parameters(op_code, param1, param2, + datalen1, data1, datalen2, data2, datalen3, data3, + tx_size, tx_buffer, rx_size, rx_buffer); + if (ret_code != SHA204_SUCCESS) + return ret_code; + + // Supply delays and response size. + switch (op_code) + { + case SHA204_CHECKMAC: + poll_delay = CHECKMAC_DELAY; + poll_timeout = CHECKMAC_EXEC_MAX - CHECKMAC_DELAY; + response_size = CHECKMAC_RSP_SIZE; + break; + + case SHA204_DERIVE_KEY: + poll_delay = DERIVE_KEY_DELAY; + poll_timeout = DERIVE_KEY_EXEC_MAX - DERIVE_KEY_DELAY; + response_size = DERIVE_KEY_RSP_SIZE; + break; + + case SHA204_DEVREV: + poll_delay = DEVREV_DELAY; + poll_timeout = DEVREV_EXEC_MAX - DEVREV_DELAY; + response_size = DEVREV_RSP_SIZE; + break; + + case SHA204_GENDIG: + poll_delay = GENDIG_DELAY; + poll_timeout = GENDIG_EXEC_MAX - GENDIG_DELAY; + response_size = GENDIG_RSP_SIZE; + break; + + case SHA204_HMAC: + poll_delay = HMAC_DELAY; + poll_timeout = HMAC_EXEC_MAX - HMAC_DELAY; + response_size = HMAC_RSP_SIZE; + break; + + case SHA204_LOCK: + poll_delay = LOCK_DELAY; + poll_timeout = LOCK_EXEC_MAX - LOCK_DELAY; + response_size = LOCK_RSP_SIZE; + break; + + case SHA204_MAC: + poll_delay = MAC_DELAY; + poll_timeout = MAC_EXEC_MAX - MAC_DELAY; + response_size = MAC_RSP_SIZE; + break; + + case SHA204_NONCE: + poll_delay = NONCE_DELAY; + poll_timeout = NONCE_EXEC_MAX - NONCE_DELAY; + response_size = param1 == NONCE_MODE_PASSTHROUGH + ? NONCE_RSP_SIZE_SHORT : NONCE_RSP_SIZE_LONG; + break; + + case SHA204_PAUSE: + poll_delay = PAUSE_DELAY; + poll_timeout = PAUSE_EXEC_MAX - PAUSE_DELAY; + response_size = PAUSE_RSP_SIZE; + break; + + case SHA204_RANDOM: + poll_delay = RANDOM_DELAY; + poll_timeout = RANDOM_EXEC_MAX - RANDOM_DELAY; + response_size = RANDOM_RSP_SIZE; + break; + + case SHA204_READ: + poll_delay = READ_DELAY; + poll_timeout = READ_EXEC_MAX - READ_DELAY; + response_size = (param1 & SHA204_ZONE_COUNT_FLAG) + ? READ_32_RSP_SIZE : READ_4_RSP_SIZE; + break; + + case SHA204_UPDATE_EXTRA: + poll_delay = UPDATE_DELAY; + poll_timeout = UPDATE_EXEC_MAX - UPDATE_DELAY; + response_size = UPDATE_RSP_SIZE; + break; + + case SHA204_WRITE: + poll_delay = WRITE_DELAY; + poll_timeout = WRITE_EXEC_MAX - WRITE_DELAY; + response_size = WRITE_RSP_SIZE; + break; + + default: + poll_delay = 0; + poll_timeout = SHA204_COMMAND_EXEC_MAX; + response_size = rx_size; + } + + // Assemble command. + len = datalen1 + datalen2 + datalen3 + SHA204_CMD_SIZE_MIN; + p_buffer = tx_buffer; + *p_buffer++ = len; + *p_buffer++ = op_code; + *p_buffer++ = param1; + *p_buffer++ = param2 & 0xFF; + *p_buffer++ = param2 >> 8; + + if (datalen1 > 0) { + memcpy(p_buffer, data1, datalen1); + p_buffer += datalen1; + } + if (datalen2 > 0) { + memcpy(p_buffer, data2, datalen2); + p_buffer += datalen2; + } + if (datalen3 > 0) { + memcpy(p_buffer, data3, datalen3); + p_buffer += datalen3; + } + + sha204c_calculate_crc(len - SHA204_CRC_SIZE, tx_buffer, p_buffer); + + // Send command and receive response. + return sha204c_send_and_receive(&tx_buffer[0], response_size, + &rx_buffer[0], poll_delay, poll_timeout); +} + +uint8_t atsha204Class::sha204m_check_parameters(uint8_t op_code, uint8_t param1, uint16_t param2, + uint8_t datalen1, uint8_t *data1, uint8_t datalen2, uint8_t *data2, uint8_t datalen3, uint8_t *data3, + uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer) +{ +#ifdef SHA204_CHECK_PARAMETERS + + uint8_t len = datalen1 + datalen2 + datalen3 + SHA204_CMD_SIZE_MIN; + if (!tx_buffer || tx_size < len || rx_size < SHA204_RSP_SIZE_MIN || !rx_buffer) + return SHA204_BAD_PARAM; + + if ((datalen1 > 0 && !data1) || (datalen2 > 0 && !data2) || (datalen3 > 0 && !data3)) + return SHA204_BAD_PARAM; + + // Check parameters depending on op-code. + switch (op_code) + { + case SHA204_CHECKMAC: + if ( + // no null pointers allowed + !data1 || !data2 + // No reserved bits should be set. + || (param1 | CHECKMAC_MODE_MASK) != CHECKMAC_MODE_MASK + // key_id > 15 not allowed + || param2 > SHA204_KEY_ID_MAX + ) + return SHA204_BAD_PARAM; + break; + + case SHA204_DERIVE_KEY: + if (param2 > SHA204_KEY_ID_MAX) + return SHA204_BAD_PARAM; + break; + + case SHA204_DEVREV: + break; + + case SHA204_GENDIG: + if ((param1 != GENDIG_ZONE_OTP) && (param1 != GENDIG_ZONE_DATA)) + return SHA204_BAD_PARAM; + break; + + case SHA204_HMAC: + if ((param1 & ~HMAC_MODE_MASK) != 0) + return SHA204_BAD_PARAM; + break; + + case SHA204_LOCK: + if (((param1 & ~LOCK_ZONE_MASK) != 0) + || ((param1 & LOCK_ZONE_NO_CRC) && (param2 != 0))) + return SHA204_BAD_PARAM; + break; + + case SHA204_MAC: + if (((param1 & ~MAC_MODE_MASK) != 0) + || (((param1 & MAC_MODE_BLOCK2_TEMPKEY) == 0) && !data1)) + return SHA204_BAD_PARAM; + break; + + case SHA204_NONCE: + if ( !data1 + || (param1 > NONCE_MODE_PASSTHROUGH) + || (param1 == NONCE_MODE_INVALID) + ) + return SHA204_BAD_PARAM; + break; + + case SHA204_PAUSE: + break; + + case SHA204_RANDOM: + if (param1 > RANDOM_NO_SEED_UPDATE) + return SHA204_BAD_PARAM; + break; + + case SHA204_READ: + if (((param1 & ~READ_ZONE_MASK) != 0) + || ((param1 & READ_ZONE_MODE_32_BYTES) && (param1 == SHA204_ZONE_OTP))) + return SHA204_BAD_PARAM; + break; + + case SHA204_TEMPSENSE: + break; + + case SHA204_UPDATE_EXTRA: + if (param1 > UPDATE_CONFIG_BYTE_86) + return SHA204_BAD_PARAM; + break; + + case SHA204_WRITE: + if (!data1 || ((param1 & ~WRITE_ZONE_MASK) != 0)) + return SHA204_BAD_PARAM; + break; + + default: + // unknown op-code + return SHA204_BAD_PARAM; + } + + return SHA204_SUCCESS; + +#else + return SHA204_SUCCESS; +#endif +} + +/* CRC Calculator and Checker */ + +void atsha204Class::sha204c_calculate_crc(uint8_t length, uint8_t *data, uint8_t *crc) +{ + uint8_t counter; + uint16_t crc_register = 0; + uint16_t polynom = 0x8005; + uint8_t shift_register; + uint8_t data_bit, crc_bit; + + for (counter = 0; counter < length; counter++) + { + for (shift_register = 0x01; shift_register > 0x00; shift_register <<= 1) + { + data_bit = (data[counter] & shift_register) ? 1 : 0; + crc_bit = crc_register >> 15; + + // Shift CRC to the left by 1. + crc_register <<= 1; + + if ((data_bit ^ crc_bit) != 0) + crc_register ^= polynom; + } + } + crc[0] = (uint8_t) (crc_register & 0x00FF); + crc[1] = (uint8_t) (crc_register >> 8); +} + +uint8_t atsha204Class::sha204c_check_crc(uint8_t *response) +{ + uint8_t crc[SHA204_CRC_SIZE]; + uint8_t count = response[SHA204_BUFFER_POS_COUNT]; + + count -= SHA204_CRC_SIZE; + sha204c_calculate_crc(count, response, crc); + + return (crc[0] == response[count] && crc[1] == response[count + 1]) + ? SHA204_SUCCESS : SHA204_BAD_CRC; +} \ No newline at end of file diff --git a/libraries/sha204/sha204_library.h b/libraries/sha204/sha204_library.h new file mode 100644 index 0000000..caf0d0b --- /dev/null +++ b/libraries/sha204/sha204_library.h @@ -0,0 +1,320 @@ +#include "Arduino.h" + +#ifndef sha204_library_H +#define sha204_library_H + +/* bitbang_config.h */ + +#define PORT_ACCESS_TIME (630) //! time it takes to toggle the pin at CPU clock of 16 MHz (ns) +#define START_PULSE_WIDTH (4340) //! width of start pulse (ns) +#define BIT_DELAY (4) //! delay macro for width of one pulse (start pulse or zero pulse, in ns) +#define RX_TX_DELAY (15) //! turn around time when switching from receive to transmit +#define START_PULSE_TIME_OUT (255) //! This value is decremented while waiting for the falling edge of a start pulse. +#define ZERO_PULSE_TIME_OUT (26) //! This value is decremented while waiting for the falling edge of a zero pulse. + +/* swi_phys.h */ + +#define SWI_FUNCTION_RETCODE_SUCCESS ((uint8_t) 0x00) //!< Communication with device succeeded. +#define SWI_FUNCTION_RETCODE_TIMEOUT ((uint8_t) 0xF1) //!< Communication timed out. +#define SWI_FUNCTION_RETCODE_RX_FAIL ((uint8_t) 0xF9) //!< Communication failed after at least one byte was received. + +/* sha204_physical.h */ + +#define SHA204_RSP_SIZE_MIN ((uint8_t) 4) //!< minimum number of bytes in response +#define SHA204_RSP_SIZE_MAX ((uint8_t) 35) //!< maximum size of response packet +#define SHA204_BUFFER_POS_COUNT (0) //!< buffer index of count byte in command or response +#define SHA204_BUFFER_POS_DATA (1) //!< buffer index of data in response +#define SHA204_WAKEUP_PULSE_WIDTH (uint8_t) (6.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5) //! width of Wakeup pulse in 10 us units +#define SHA204_WAKEUP_DELAY (uint8_t) (3.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5) //! delay between Wakeup pulse and communication in ms + +/* sha204_swi.c */ +#define SHA204_SWI_FLAG_CMD ((uint8_t) 0x77) //!< flag preceding a command +#define SHA204_SWI_FLAG_TX ((uint8_t) 0x88) //!< flag requesting a response +#define SHA204_SWI_FLAG_IDLE ((uint8_t) 0xBB) //!< flag requesting to go into Idle mode +#define SHA204_SWI_FLAG_SLEEP ((uint8_t) 0xCC) //!< flag requesting to go into Sleep mode + +/* sha204_comm_marshaling.h */ +// command op-code definitions +#define SHA204_CHECKMAC ((uint8_t) 0x28) //!< CheckMac command op-code +#define SHA204_DERIVE_KEY ((uint8_t) 0x1C) //!< DeriveKey command op-code +#define SHA204_DEVREV ((uint8_t) 0x30) //!< DevRev command op-code +#define SHA204_GENDIG ((uint8_t) 0x15) //!< GenDig command op-code +#define SHA204_HMAC ((uint8_t) 0x11) //!< HMAC command op-code +#define SHA204_LOCK ((uint8_t) 0x17) //!< Lock command op-code +#define SHA204_MAC ((uint8_t) 0x08) //!< MAC command op-code +#define SHA204_NONCE ((uint8_t) 0x16) //!< Nonce command op-code +#define SHA204_PAUSE ((uint8_t) 0x01) //!< Pause command op-code +#define SHA204_RANDOM ((uint8_t) 0x1B) //!< Random command op-code +#define SHA204_READ ((uint8_t) 0x02) //!< Read command op-code +#define SHA204_UPDATE_EXTRA ((uint8_t) 0x20) //!< UpdateExtra command op-code +#define SHA204_WRITE ((uint8_t) 0x12) //!< Write command op-code + +// packet size definitions +#define SHA204_RSP_SIZE_VAL ((uint8_t) 7) //!< size of response packet containing four bytes of data + +// parameter range definitions +#define SHA204_KEY_ID_MAX ((uint8_t) 15) //!< maximum value for key id +#define SHA204_OTP_BLOCK_MAX ((uint8_t) 1) //!< maximum value for OTP block + +// definitions for command packet indexes common to all commands +#define SHA204_COUNT_IDX ( 0) //!< command packet index for count +#define SHA204_OPCODE_IDX ( 1) //!< command packet index for op-code +#define SHA204_PARAM1_IDX ( 2) //!< command packet index for first parameter +#define SHA204_PARAM2_IDX ( 3) //!< command packet index for second parameter +#define SHA204_DATA_IDX ( 5) //!< command packet index for second parameter + +// zone definitions +#define SHA204_ZONE_CONFIG ((uint8_t) 0x00) //!< Configuration zone +#define SHA204_ZONE_OTP ((uint8_t) 0x01) //!< OTP (One Time Programming) zone +#define SHA204_ZONE_DATA ((uint8_t) 0x02) //!< Data zone +#define SHA204_ZONE_MASK ((uint8_t) 0x03) //!< Zone mask +#define SHA204_ZONE_COUNT_FLAG ((uint8_t) 0x80) //!< Zone bit 7 set: Access 32 bytes, otherwise 4 bytes. +#define SHA204_ZONE_ACCESS_4 ((uint8_t) 4) //!< Read or write 4 bytes. +#define SHA204_ZONE_ACCESS_32 ((uint8_t) 32) //!< Read or write 32 bytes. +#define SHA204_ADDRESS_MASK_CONFIG ( 0x001F) //!< Address bits 5 to 7 are 0 for Configuration zone. +#define SHA204_ADDRESS_MASK_OTP ( 0x000F) //!< Address bits 4 to 7 are 0 for OTP zone. +#define SHA204_ADDRESS_MASK ( 0x007F) //!< Address bit 7 to 15 are always 0. + +// CheckMAC command definitions +#define CHECKMAC_MODE_IDX SHA204_PARAM1_IDX //!< CheckMAC command index for mode +#define CHECKMAC_KEYID_IDX SHA204_PARAM2_IDX //!< CheckMAC command index for key identifier +#define CHECKMAC_CLIENT_CHALLENGE_IDX SHA204_DATA_IDX //!< CheckMAC command index for client challenge +#define CHECKMAC_CLIENT_RESPONSE_IDX (37) //!< CheckMAC command index for client response +#define CHECKMAC_DATA_IDX (69) //!< CheckMAC command index for other data +#define CHECKMAC_COUNT (84) //!< CheckMAC command packet size +#define CHECKMAC_MODE_MASK ((uint8_t) 0x27) //!< CheckMAC mode bits 3, 4, 6, and 7 are 0. +#define CHECKMAC_CLIENT_CHALLENGE_SIZE (32) //!< CheckMAC size of client challenge +#define CHECKMAC_CLIENT_RESPONSE_SIZE (32) //!< CheckMAC size of client response +#define CHECKMAC_OTHER_DATA_SIZE (13) //!< CheckMAC size of "other data" + +// DeriveKey command definitions +#define DERIVE_KEY_RANDOM_IDX SHA204_PARAM1_IDX //!< DeriveKey command index for random bit +#define DERIVE_KEY_TARGETKEY_IDX SHA204_PARAM2_IDX //!< DeriveKey command index for target slot +#define DERIVE_KEY_MAC_IDX SHA204_DATA_IDX //!< DeriveKey command index for optional MAC +#define DERIVE_KEY_COUNT_SMALL SHA204_CMD_SIZE_MIN //!< DeriveKey command packet size without MAC +#define DERIVE_KEY_COUNT_LARGE (39) //!< DeriveKey command packet size with MAC +#define DERIVE_KEY_RANDOM_FLAG ((uint8_t) 4) //!< DeriveKey 1. parameter +#define DERIVE_KEY_MAC_SIZE (32) //!< DeriveKey MAC size + +// DevRev command definitions +#define DEVREV_PARAM1_IDX SHA204_PARAM1_IDX //!< DevRev command index for 1. parameter (ignored) +#define DEVREV_PARAM2_IDX SHA204_PARAM2_IDX //!< DevRev command index for 2. parameter (ignored) +#define DEVREV_COUNT SHA204_CMD_SIZE_MIN //!< DevRev command packet size + +// GenDig command definitions +#define GENDIG_ZONE_IDX SHA204_PARAM1_IDX //!< GenDig command index for zone +#define GENDIG_KEYID_IDX SHA204_PARAM2_IDX //!< GenDig command index for key id +#define GENDIG_DATA_IDX SHA204_DATA_IDX //!< GenDig command index for optional data +#define GENDIG_COUNT SHA204_CMD_SIZE_MIN //!< GenDig command packet size without "other data" +#define GENDIG_COUNT_DATA (11) //!< GenDig command packet size with "other data" +#define GENDIG_OTHER_DATA_SIZE (4) //!< GenDig size of "other data" +#define GENDIG_ZONE_CONFIG ((uint8_t) 0) //!< GenDig zone id config +#define GENDIG_ZONE_OTP ((uint8_t) 1) //!< GenDig zone id OTP +#define GENDIG_ZONE_DATA ((uint8_t) 2) //!< GenDig zone id data + +// HMAC command definitions +#define HMAC_MODE_IDX SHA204_PARAM1_IDX //!< HMAC command index for mode +#define HMAC_KEYID_IDX SHA204_PARAM2_IDX //!< HMAC command index for key id +#define HMAC_COUNT SHA204_CMD_SIZE_MIN //!< HMAC command packet size +#define HMAC_MODE_MASK ((uint8_t) 0x74) //!< HMAC mode bits 0, 1, 3, and 7 are 0. + +// Lock command definitions +#define LOCK_ZONE_IDX SHA204_PARAM1_IDX //!< Lock command index for zone +#define LOCK_SUMMARY_IDX SHA204_PARAM2_IDX //!< Lock command index for summary +#define LOCK_COUNT SHA204_CMD_SIZE_MIN //!< Lock command packet size +#define LOCK_ZONE_NO_CONFIG ((uint8_t) 0x01) //!< Lock zone is OTP or Data +#define LOCK_ZONE_NO_CRC ((uint8_t) 0x80) //!< Lock command: Ignore summary. +#define LOCK_ZONE_MASK (0x81) //!< Lock parameter 1 bits 2 to 6 are 0. + +// Mac command definitions +#define MAC_MODE_IDX SHA204_PARAM1_IDX //!< MAC command index for mode +#define MAC_KEYID_IDX SHA204_PARAM2_IDX //!< MAC command index for key id +#define MAC_CHALLENGE_IDX SHA204_DATA_IDX //!< MAC command index for optional challenge +#define MAC_COUNT_SHORT SHA204_CMD_SIZE_MIN //!< MAC command packet size without challenge +#define MAC_COUNT_LONG (39) //!< MAC command packet size with challenge +#define MAC_MODE_BLOCK2_TEMPKEY ((uint8_t) 0x01) //!< MAC mode bit 0: second SHA block from TempKey +#define MAC_MODE_BLOCK1_TEMPKEY ((uint8_t) 0x02) //!< MAC mode bit 1: first SHA block from TempKey +#define MAC_MODE_SOURCE_FLAG_MATCH ((uint8_t) 0x04) //!< MAC mode bit 2: match TempKey.SourceFlag +#define MAC_MODE_PASSTHROUGH ((uint8_t) 0x07) //!< MAC mode bit 0-2: pass-through mode +#define MAC_MODE_INCLUDE_OTP_88 ((uint8_t) 0x10) //!< MAC mode bit 4: include first 88 OTP bits +#define MAC_MODE_INCLUDE_OTP_64 ((uint8_t) 0x20) //!< MAC mode bit 5: include first 64 OTP bits +#define MAC_MODE_INCLUDE_SN ((uint8_t) 0x40) //!< MAC mode bit 6: include serial number +#define MAC_CHALLENGE_SIZE (32) //!< MAC size of challenge +#define MAC_MODE_MASK ((uint8_t) 0x77) //!< MAC mode bits 3 and 7 are 0. + +// Nonce command definitions +#define NONCE_MODE_IDX SHA204_PARAM1_IDX //!< Nonce command index for mode +#define NONCE_PARAM2_IDX SHA204_PARAM2_IDX //!< Nonce command index for 2. parameter +#define NONCE_INPUT_IDX SHA204_DATA_IDX //!< Nonce command index for input data +#define NONCE_COUNT_SHORT (27) //!< Nonce command packet size for 20 bytes of data +#define NONCE_COUNT_LONG (39) //!< Nonce command packet size for 32 bytes of data +#define NONCE_MODE_MASK ((uint8_t) 3) //!< Nonce mode bits 2 to 7 are 0. +#define NONCE_MODE_SEED_UPDATE ((uint8_t) 0x00) //!< Nonce mode: update seed +#define NONCE_MODE_NO_SEED_UPDATE ((uint8_t) 0x01) //!< Nonce mode: do not update seed +#define NONCE_MODE_INVALID ((uint8_t) 0x02) //!< Nonce mode 2 is invalid. +#define NONCE_MODE_PASSTHROUGH ((uint8_t) 0x03) //!< Nonce mode: pass-through +#define NONCE_NUMIN_SIZE (20) //!< Nonce data length +#define NONCE_NUMIN_SIZE_PASSTHROUGH (32) //!< Nonce data length in pass-through mode (mode = 3) + +// Pause command definitions +#define PAUSE_SELECT_IDX SHA204_PARAM1_IDX //!< Pause command index for Selector +#define PAUSE_PARAM2_IDX SHA204_PARAM2_IDX //!< Pause command index for 2. parameter +#define PAUSE_COUNT SHA204_CMD_SIZE_MIN //!< Pause command packet size + +// Random command definitions +#define RANDOM_MODE_IDX SHA204_PARAM1_IDX //!< Random command index for mode +#define RANDOM_PARAM2_IDX SHA204_PARAM2_IDX //!< Random command index for 2. parameter +#define RANDOM_COUNT SHA204_CMD_SIZE_MIN //!< Random command packet size +#define RANDOM_SEED_UPDATE ((uint8_t) 0x00) //!< Random mode for automatic seed update +#define RANDOM_NO_SEED_UPDATE ((uint8_t) 0x01) //!< Random mode for no seed update + +// Read command definitions +#define READ_ZONE_IDX SHA204_PARAM1_IDX //!< Read command index for zone +#define READ_ADDR_IDX SHA204_PARAM2_IDX //!< Read command index for address +#define READ_COUNT SHA204_CMD_SIZE_MIN //!< Read command packet size +#define READ_ZONE_MASK ((uint8_t) 0x83) //!< Read zone bits 2 to 6 are 0. +#define READ_ZONE_MODE_32_BYTES ((uint8_t) 0x80) //!< Read mode: 32 bytes + +// UpdateExtra command definitions +#define UPDATE_MODE_IDX SHA204_PARAM1_IDX //!< UpdateExtra command index for mode +#define UPDATE_VALUE_IDX SHA204_PARAM2_IDX //!< UpdateExtra command index for new value +#define UPDATE_COUNT SHA204_CMD_SIZE_MIN //!< UpdateExtra command packet size +#define UPDATE_CONFIG_BYTE_86 ((uint8_t) 0x01) //!< UpdateExtra mode: update Config byte 86 + +// Write command definitions +#define WRITE_ZONE_IDX SHA204_PARAM1_IDX //!< Write command index for zone +#define WRITE_ADDR_IDX SHA204_PARAM2_IDX //!< Write command index for address +#define WRITE_VALUE_IDX SHA204_DATA_IDX //!< Write command index for data +#define WRITE_MAC_VS_IDX ( 9) //!< Write command index for MAC following short data +#define WRITE_MAC_VL_IDX (37) //!< Write command index for MAC following long data +#define WRITE_COUNT_SHORT (11) //!< Write command packet size with short data and no MAC +#define WRITE_COUNT_LONG (39) //!< Write command packet size with long data and no MAC +#define WRITE_COUNT_SHORT_MAC (43) //!< Write command packet size with short data and MAC +#define WRITE_COUNT_LONG_MAC (71) //!< Write command packet size with long data and MAC +#define WRITE_MAC_SIZE (32) //!< Write MAC size +#define WRITE_ZONE_MASK ((uint8_t) 0xC3) //!< Write zone bits 2 to 5 are 0. +#define WRITE_ZONE_WITH_MAC ((uint8_t) 0x40) //!< Write zone bit 6: write encrypted with MAC + +// Response size definitions +#define CHECKMAC_RSP_SIZE SHA204_RSP_SIZE_MIN //!< response size of DeriveKey command +#define DERIVE_KEY_RSP_SIZE SHA204_RSP_SIZE_MIN //!< response size of DeriveKey command +#define DEVREV_RSP_SIZE SHA204_RSP_SIZE_VAL //!< response size of DevRev command returns 4 bytes +#define GENDIG_RSP_SIZE SHA204_RSP_SIZE_MIN //!< response size of GenDig command +#define HMAC_RSP_SIZE SHA204_RSP_SIZE_MAX //!< response size of HMAC command +#define LOCK_RSP_SIZE SHA204_RSP_SIZE_MIN //!< response size of Lock command +#define MAC_RSP_SIZE SHA204_RSP_SIZE_MAX //!< response size of MAC command +#define NONCE_RSP_SIZE_SHORT SHA204_RSP_SIZE_MIN //!< response size of Nonce command with mode[0:1] = 3 +#define NONCE_RSP_SIZE_LONG SHA204_RSP_SIZE_MAX //!< response size of Nonce command +#define PAUSE_RSP_SIZE SHA204_RSP_SIZE_MIN //!< response size of Pause command +#define RANDOM_RSP_SIZE SHA204_RSP_SIZE_MAX //!< response size of Random command +#define READ_4_RSP_SIZE SHA204_RSP_SIZE_VAL //!< response size of Read command when reading 4 bytes +#define READ_32_RSP_SIZE SHA204_RSP_SIZE_MAX //!< response size of Read command when reading 32 bytes +#define TEMP_SENSE_RSP_SIZE SHA204_RSP_SIZE_VAL //!< response size of TempSense command returns 4 bytes +#define UPDATE_RSP_SIZE SHA204_RSP_SIZE_MIN //!< response size of UpdateExtra command +#define WRITE_RSP_SIZE SHA204_RSP_SIZE_MIN //!< response size of Write command + +// command timing definitions for minimum execution times (ms) +#define CHECKMAC_DELAY ((uint8_t) (12.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define DERIVE_KEY_DELAY ((uint8_t) (14.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define DEVREV_DELAY ((uint8_t) ( 0.4 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define GENDIG_DELAY ((uint8_t) (11.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define HMAC_DELAY ((uint8_t) (27.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define LOCK_DELAY ((uint8_t) ( 5.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define MAC_DELAY ((uint8_t) (12.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define NONCE_DELAY ((uint8_t) (22.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define PAUSE_DELAY ((uint8_t) ( 0.4 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define RANDOM_DELAY ((uint8_t) (11.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define READ_DELAY ((uint8_t) ( 0.4 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define TEMP_SENSE_DELAY ((uint8_t) ( 4.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define UPDATE_DELAY ((uint8_t) ( 4.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define WRITE_DELAY ((uint8_t) ( 4.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) + +// command timing definitions for maximum execution times (ms) +#define CHECKMAC_EXEC_MAX ((uint8_t) (38.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define DERIVE_KEY_EXEC_MAX ((uint8_t) (62.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define DEVREV_EXEC_MAX ((uint8_t) ( 2.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define GENDIG_EXEC_MAX ((uint8_t) (43.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define HMAC_EXEC_MAX ((uint8_t) (69.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define LOCK_EXEC_MAX ((uint8_t) (24.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define MAC_EXEC_MAX ((uint8_t) (35.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define NONCE_EXEC_MAX ((uint8_t) (60.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define PAUSE_EXEC_MAX ((uint8_t) ( 2.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define RANDOM_EXEC_MAX ((uint8_t) (50.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define READ_EXEC_MAX ((uint8_t) ( 4.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define TEMP_SENSE_EXEC_MAX ((uint8_t) (11.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define UPDATE_EXEC_MAX ((uint8_t) ( 6.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define WRITE_EXEC_MAX ((uint8_t) (42.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) + +/* from sha204_config.h */ + +#define CPU_CLOCK_DEVIATION_POSITIVE (1.01) +#define CPU_CLOCK_DEVIATION_NEGATIVE (0.99) +#define SHA204_RETRY_COUNT (1) +#define SWI_RECEIVE_TIME_OUT ((uint16_t) 163) //! #START_PULSE_TIME_OUT in us instead of loop counts +#define SWI_US_PER_BYTE ((uint16_t) 313) //! It takes 312.5 us to send a byte (9 single-wire bits / 230400 Baud * 8 flag bits). +#define SHA204_SYNC_TIMEOUT ((uint8_t) 85)//! delay before sending a transmit flag in the synchronization routine +#define SHA204_RESPONSE_TIMEOUT ((uint16_t) SWI_RECEIVE_TIME_OUT + SWI_US_PER_BYTE) //! SWI response timeout is the sum of receive timeout and the time it takes to send the TX flag. + +/* from sha204_comm.h */ + +#define SHA204_COMMAND_EXEC_MAX ((uint8_t) (69.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) //! maximum command delay +#define SHA204_CMD_SIZE_MIN ((uint8_t) 7) //! minimum number of bytes in command (from count byte to second CRC byte) +#define SHA204_CMD_SIZE_MAX ((uint8_t) 84) //! maximum size of command packet (CheckMac) +#define SHA204_CRC_SIZE ((uint8_t) 2) //! number of CRC bytes +#define SHA204_BUFFER_POS_STATUS (1) //! buffer index of status byte in status response +#define SHA204_BUFFER_POS_DATA (1) //! buffer index of first data byte in data response +#define SHA204_STATUS_BYTE_WAKEUP ((uint8_t) 0x11) //! command parse error +#define SHA204_STATUS_BYTE_PARSE ((uint8_t) 0x03) //! command parse error +#define SHA204_STATUS_BYTE_EXEC ((uint8_t) 0x0F) //! command execution error +#define SHA204_STATUS_BYTE_COMM ((uint8_t) 0xFF) //! communication error + +/* EEPROM Addresses */ +/* Configuration Zone */ +#define ADDRESS_SN03 0 // SN[0:3] are bytes 0->3 of configuration zone +#define ADDRESS_RevNum 4 // bytes 4->7 of config zone are RevNum +#define ADDRESS_SN47 8 // SN[4:7] are bytes 8->11 of config zone +#define ADDRESS_SN8 12 // SN[8] is byte 12 of config zone, should be 0xEE +#define ADDRESS_I2CEN 14 // I2C Enable, bit 0 represents I2C enable status +#define ADDRESS_I2CADD 16 // Defines I2C address of SHA204 +#define ADDRESS_OTPMODE 18 // Sets the One-time-programmable mode +#define ADDRESS_SELECTOR 19 // Controls writability of Selector + + +class atsha204Class +{ +private: + uint8_t device_pin; + volatile uint8_t *device_port_DDR, *device_port_OUT, *device_port_IN; + void sha204c_calculate_crc(uint8_t length, uint8_t *data, uint8_t *crc); + uint8_t sha204c_check_crc(uint8_t *response); + void swi_set_signal_pin(uint8_t is_high); + uint8_t swi_receive_bytes(uint8_t count, uint8_t *buffer); + uint8_t swi_send_bytes(uint8_t count, uint8_t *buffer); + uint8_t swi_send_byte(uint8_t value); + uint8_t sha204p_receive_response(uint8_t size, uint8_t *response); + uint8_t sha204p_wakeup(); + uint8_t sha204p_send_command(uint8_t count, uint8_t * command); + uint8_t sha204p_sleep(); + uint8_t sha204p_resync(uint8_t size, uint8_t *response); + + +public: + atsha204Class(uint8_t pin); // Constructor + uint8_t sha204c_wakeup(uint8_t *response); + uint8_t sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer, uint8_t execution_delay, uint8_t execution_timeout); + uint8_t sha204c_resync(uint8_t size, uint8_t *response); + uint8_t sha204m_random(uint8_t * tx_buffer, uint8_t * rx_buffer, uint8_t mode); + uint8_t sha204m_dev_rev(uint8_t *tx_buffer, uint8_t *rx_buffer); + uint8_t sha204m_read(uint8_t *tx_buffer, uint8_t *rx_buffer, uint8_t zone, uint16_t address); + uint8_t sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t param2, + uint8_t datalen1, uint8_t *data1, uint8_t datalen2, uint8_t *data2, uint8_t datalen3, uint8_t *data3, + uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer); + uint8_t sha204m_check_parameters(uint8_t op_code, uint8_t param1, uint16_t param2, + uint8_t datalen1, uint8_t *data1, uint8_t datalen2, uint8_t *data2, uint8_t datalen3, uint8_t *data3, + uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer); + + uint8_t getSerialNumber(uint8_t *response); + +}; + +#endif From 1ac6f0a2916ecad0b0372592e558c3f56d32d52d Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 10 Jan 2015 12:33:27 +0100 Subject: [PATCH 026/137] Removed examples from sha204 libraries MySensors will have native support for sha204 and the source for usage and personalization of sha204 will be much more elaborate than this example so it does not provide additional understanding for the chip. --- .../atsha204_simple_example.ino | 103 ------------------ 1 file changed, 103 deletions(-) delete mode 100644 libraries/sha204/examples/atsha204_simple_example/atsha204_simple_example.ino diff --git a/libraries/sha204/examples/atsha204_simple_example/atsha204_simple_example.ino b/libraries/sha204/examples/atsha204_simple_example/atsha204_simple_example.ino deleted file mode 100644 index b55ce49..0000000 --- a/libraries/sha204/examples/atsha204_simple_example/atsha204_simple_example.ino +++ /dev/null @@ -1,103 +0,0 @@ -/* ATSHA204 Library Simple Example - by: Jim Lindblom - SparkFun Electronics - date: November 8, 2012 - - This code shows how to wake up and verify that an SHA204 is - connected and operational. And how to obtain an SHA204's unique serial - number, and send it a MAC challenge. - - The ATSHA204's SDA pin can be connected to any of the Arduino's digital pins. - When constructing your atsha204Class, pass the constructor the pin you want to use. - In this example we'll attach SDA to pin 7. - - The ATSHA204 can be powered between 3.3V and 5V. -*/ -#include - -const int sha204Pin = 7; - -atsha204Class sha204(sha204Pin); - -void setup() -{ - Serial.begin(9600); - Serial.println("Sending a Wakup Command. Response should be:\r\n4 11 33 43:"); - Serial.println("Response is:"); - wakeupExample(); - Serial.println(); - Serial.println("Asking the SHA204's serial number. Response should be:"); - Serial.println("1 23 x x x x x x x EE"); - Serial.println("Response is:"); - serialNumberExample(); - Serial.println(); - Serial.println("Sending a MAC Challenge. Response should be:"); - Serial.println("23 6 67 0 4F 28 4D 6E 98 62 4 F4 60 A3 E8 75 8A 59 85 A6 79 96 C4 8A 88 46 43 4E B3 DB 58 A4 FB E5 73"); - Serial.println("Response is:"); - macChallengeExample(); -} - -void loop() -{ -} - -byte wakeupExample() -{ - uint8_t response[SHA204_RSP_SIZE_MIN]; - byte returnValue; - - returnValue = sha204.sha204c_wakeup(&response[0]); - for (int i=0; i Date: Sat, 10 Jan 2015 18:17:32 +0100 Subject: [PATCH 027/137] sha204 library extended with CRC calculator Locking operations are recommended to include CRC and since sha204 library internally carries the proper algorithm for this, it has now been refactored to support both static and incremental calculations needed for both command marchalling and locking. --- libraries/sha204/sha204_library.cpp | 46 ++++++++++++++++++----------- libraries/sha204/sha204_library.h | 1 + 2 files changed, 29 insertions(+), 18 deletions(-) diff --git a/libraries/sha204/sha204_library.cpp b/libraries/sha204/sha204_library.cpp index 075242f..44e59bd 100644 --- a/libraries/sha204/sha204_library.cpp +++ b/libraries/sha204/sha204_library.cpp @@ -50,6 +50,33 @@ uint8_t atsha204Class::getSerialNumber(uint8_t * response) return returnCode; } +/* Calculates CRC16 value of provided data (and optionally including provided existing CRC16 data) + returns the calculated CRC16 value */ +uint16_t atsha204Class::calculateAndUpdateCrc(uint8_t length, uint8_t *data, uint16_t current_crc) +{ + uint8_t counter; + uint16_t crc_register = current_crc; + uint16_t polynom = 0x8005; + uint8_t shift_register; + uint8_t data_bit, crc_bit; + + for (counter = 0; counter < length; counter++) + { + for (shift_register = 0x01; shift_register > 0x00; shift_register <<= 1) + { + data_bit = (data[counter] & shift_register) ? 1 : 0; + crc_bit = crc_register >> 15; + + // Shift CRC to the left by 1. + crc_register <<= 1; + + if ((data_bit ^ crc_bit) != 0) + crc_register ^= polynom; + } + } + return crc_register; +} + /* SWI bit bang functions */ void atsha204Class::swi_set_signal_pin(uint8_t is_high) @@ -772,26 +799,9 @@ uint8_t atsha204Class::sha204m_check_parameters(uint8_t op_code, uint8_t param1, void atsha204Class::sha204c_calculate_crc(uint8_t length, uint8_t *data, uint8_t *crc) { - uint8_t counter; uint16_t crc_register = 0; - uint16_t polynom = 0x8005; - uint8_t shift_register; - uint8_t data_bit, crc_bit; - for (counter = 0; counter < length; counter++) - { - for (shift_register = 0x01; shift_register > 0x00; shift_register <<= 1) - { - data_bit = (data[counter] & shift_register) ? 1 : 0; - crc_bit = crc_register >> 15; - - // Shift CRC to the left by 1. - crc_register <<= 1; - - if ((data_bit ^ crc_bit) != 0) - crc_register ^= polynom; - } - } + crc_register = calculateAndUpdateCrc(length, data, crc_register); crc[0] = (uint8_t) (crc_register & 0x00FF); crc[1] = (uint8_t) (crc_register >> 8); } diff --git a/libraries/sha204/sha204_library.h b/libraries/sha204/sha204_library.h index caf0d0b..3e2c9f0 100644 --- a/libraries/sha204/sha204_library.h +++ b/libraries/sha204/sha204_library.h @@ -314,6 +314,7 @@ public: uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer); uint8_t getSerialNumber(uint8_t *response); + uint16_t calculateAndUpdateCrc(uint8_t length, uint8_t *data, uint16_t current_crc); }; From 6aa370d6f21ceca89ec79bcc8caecbd969b8e362 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 10 Jan 2015 18:42:04 +0100 Subject: [PATCH 028/137] Personalization sketch for ATSHA204 This sketch is used to personalize the ATSHA204 crypto circuit. This is required in order to use the device for secure communication. The sketch also supports random key generation. To personalize a ATSHA204 device, do the following: 1. Ensure the correct pin is used for the ATSHA204. 2. Execute the sketch without other changes to verify that it can communicate properly with the device. 3g. For a device used in a gateway: Enable LOCK_CONFIGURATION to lock the configuration and enable random key generation as well as key storage. 4g. Execute the sketch to lock the configuration and obtain a unique key. Be sure to note down the key printed in the UART log as it has been stored in the chip and will never be accessible again (a new key is calculated on subsequent runs). The key can still be changed. 5g. Enable SKIP_KEY_STORAGE to prevent generating new random keys on sketch re-execution. 3n. For a device used as a node: Enable USER_KEY_DATA and enter your private key data in user_key_data. Then enable LOCK_CONFIGURATION to lock the configuration 4n. Execute the sketch to lock the configuration and store the user-supplied key. 5n. Optionally: Enable SKIP_KEY_STORAGE to prevent re-writing the user supplied key on sketch re-execution. 6. Optionally: Enable LOCK_DATA to prevent the key to be changed. --- .../sha204_personalizer.ino | 947 ++++++++++++++++++ 1 file changed, 947 insertions(+) create mode 100644 libraries/sha204/examples/sha204_personalizer/sha204_personalizer.ino diff --git a/libraries/sha204/examples/sha204_personalizer/sha204_personalizer.ino b/libraries/sha204/examples/sha204_personalizer/sha204_personalizer.ino new file mode 100644 index 0000000..771d024 --- /dev/null +++ b/libraries/sha204/examples/sha204_personalizer/sha204_personalizer.ino @@ -0,0 +1,947 @@ +/* SHA204 personalization sketch + by: Patrick Fallberg + date: January 10, 2015 + + This sketch will write factory default settings to the configuration zone + and then lock it. + It will then either + a. Generate a random value to use as a key which will be stored in + slot 0. The key is printed on UART (115200) in clear text for the user to be + able to use it as a user-supplied key in other personalization executions + where the same key is needed. + b. Use a user-supplied value to use as a key which will be stored in + slot 0. + Finally it will lock the data zone. + + By default, no locking is performed. User have to manually enable the flags that + turn on the locking. Furthermore, user have to send a SPACE character on serial + console when prompted to do any locking. + Default settings use ATSHA204 on pin 7. +*/ +#include +#include + +// The pin the ATSHA204 is connected on +#define ATSHA204_PIN 7 + +// Uncomment this to enable locking the configuration zone. +// *** BE AWARE THAT THIS PREVENTS ANY FUTURE CONFIGURATION CHANGE TO THE CHIP *** +// It is still possible to change the key, and this also enable random key generation +//#define LOCK_CONFIGURATION + +// Uncomment this to enable locking the data zone. +// *** BE AWARE THAT THIS PREVENTS THE KEY TO BE CHANGED *** +// It is not required to lock data, key cannot be retrieved anyway, but by locking +// data, it can be guaranteed that nobody even with physical access to the chip, +// will be able to change the key. +//#define LOCK_DATA + +// Uncomment this to skip key storage (typically once key has been written once) +//#define SKIP_KEY_STORAGE + +// Uncomment this to skip key data storage (once configuration is locked, key +// will aways randomize ) +// Uncomment this to skip key generation and use 'user_key_data' as key instead. +//#define USER_KEY_DATA + +#ifdef USER_KEY_DATA +const uint8_t user_key_data[32] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +#endif + +const int sha204Pin = ATSHA204_PIN; +atsha204Class sha204(sha204Pin); + +void halt() +{ + Serial.println(F("Halting!")); + while(1); +} + +uint16_t write_config_and_get_crc() +{ + uint16_t crc = 0; + uint8_t config_word[4]; + uint8_t tx_buffer[SHA204_CMD_SIZE_MAX]; + uint8_t rx_buffer[SHA204_RSP_SIZE_MAX]; + uint8_t ret_code; + bool do_write; + + // We will set default settings from datasheet on all slots. This means that we can use slot 0 for the key + // as that slot will not be readable (key will therefore be secure) and slot 8 for the payload digest + // calculationon as that slot can be written in clear text even when the datazone is locked. + // Other settings which are not relevant are kept as is. + + for (int i=0; i < 88; i += 4) + { + do_write = true; + if (i == 20) + { + config_word[0] = 0x8F; + config_word[1] = 0x80; + config_word[2] = 0x80; + config_word[3] = 0xA1; + } + else if (i == 24) + { + config_word[0] = 0x82; + config_word[1] = 0xE0; + config_word[2] = 0xA3; + config_word[3] = 0x60; + } + else if (i == 28) + { + config_word[0] = 0x94; + config_word[1] = 0x40; + config_word[2] = 0xA0; + config_word[3] = 0x85; + } + else if (i == 32) + { + config_word[0] = 0x86; + config_word[1] = 0x40; + config_word[2] = 0x87; + config_word[3] = 0x07; + } + else if (i == 36) + { + config_word[0] = 0x0F; + config_word[1] = 0x00; + config_word[2] = 0x89; + config_word[3] = 0xF2; + } + else if (i == 40) + { + config_word[0] = 0x8A; + config_word[1] = 0x7A; + config_word[2] = 0x0B; + config_word[3] = 0x8B; + } + else if (i == 44) + { + config_word[0] = 0x0C; + config_word[1] = 0x4C; + config_word[2] = 0xDD; + config_word[3] = 0x4D; + } + else if (i == 48) + { + config_word[0] = 0xC2; + config_word[1] = 0x42; + config_word[2] = 0xAF; + config_word[3] = 0x8F; + } + else if (i == 52 || i == 56 || i == 60 || i == 64) + { + config_word[0] = 0xFF; + config_word[1] = 0x00; + config_word[2] = 0xFF; + config_word[3] = 0x00; + } + else if (i == 68 || i == 72 || i == 76 || i == 80) + { + config_word[0] = 0xFF; + config_word[1] = 0xFF; + config_word[2] = 0xFF; + config_word[3] = 0xFF; + } + else + { + // All other configs are untouched + ret_code = sha204.sha204m_read(tx_buffer, rx_buffer, SHA204_ZONE_CONFIG, i); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Failed to read config. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + // Set config_word to the read data + config_word[0] = rx_buffer[SHA204_BUFFER_POS_DATA+0]; + config_word[1] = rx_buffer[SHA204_BUFFER_POS_DATA+1]; + config_word[2] = rx_buffer[SHA204_BUFFER_POS_DATA+2]; + config_word[3] = rx_buffer[SHA204_BUFFER_POS_DATA+3]; + do_write = false; + } + + // Update crc with CRC for the current word + crc = sha204.calculateAndUpdateCrc(4, config_word, crc); + + // Write config word + if (do_write) + { + ret_code = sha204.sha204m_execute(SHA204_WRITE, SHA204_ZONE_CONFIG, + i >> 2, 4, config_word, 0, NULL, 0, NULL, + WRITE_COUNT_SHORT, tx_buffer, WRITE_RSP_SIZE, rx_buffer); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Failed to write config word at address ")); Serial.print(i); + Serial.print(F(". Response: ")); Serial.println(ret_code, HEX); + halt(); + } + } + } + return crc; +} + +void write_key(uint8_t* key) +{ + uint8_t tx_buffer[SHA204_CMD_SIZE_MAX]; + uint8_t rx_buffer[SHA204_RSP_SIZE_MAX]; + uint8_t ret_code; + + // Write key to slot 0 + ret_code = sha204.sha204m_execute(SHA204_WRITE, SHA204_ZONE_DATA | SHA204_ZONE_COUNT_FLAG, + 0, SHA204_ZONE_ACCESS_32, key, 0, NULL, 0, NULL, + WRITE_COUNT_LONG, tx_buffer, WRITE_RSP_SIZE, rx_buffer); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Failed to write key to slot 0. Response: ")); Serial.println(ret_code, HEX); + halt(); + } +} + +void dump_configuration() +{ + uint8_t config_word[4]; + uint8_t tx_buffer[SHA204_CMD_SIZE_MAX]; + uint8_t rx_buffer[SHA204_RSP_SIZE_MAX]; + uint8_t ret_code; + + for (int i=0; i < 88; i += 4) + { + ret_code = sha204.sha204m_read(tx_buffer, rx_buffer, SHA204_ZONE_CONFIG, i); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Failed to read config. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + if (i == 0x00) + { + Serial.print(F(" SN[0:1] | SN[2:3] | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j == 1) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x04) + { + Serial.print(F(" Revnum | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + Serial.print(F(" ")); + } + Serial.println(); + } + else if (i == 0x08) + { + Serial.print(F(" SN[4:7] | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + Serial.print(F(" ")); + } + Serial.println(); + } + else if (i == 0x0C) + { + Serial.print(F(" SN[8] | Reserved13 | I2CEnable | Reserved15 | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j < 3) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x10) + { + Serial.print(F(" I2CAddress | TempOffset | OTPmode | SelectorMode | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j < 3) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x14) + { + Serial.print(F(" SlotConfig00 | SlotConfig01 | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j == 1) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x18) + { + Serial.print(F(" SlotConfig02 | SlotConfig03 | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j == 1) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x1C) + { + Serial.print(F(" SlotConfig04 | SlotConfig05 | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j == 1) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x20) + { + Serial.print(F(" SlotConfig06 | SlotConfig07 | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j == 1) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x24) + { + Serial.print(F(" SlotConfig08 | SlotConfig09 | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j == 1) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x28) + { + Serial.print(F(" SlotConfig0A | SlotConfig0B | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j == 1) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x2C) + { + Serial.print(F(" SlotConfig0C | SlotConfig0D | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j == 1) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x30) + { + Serial.print(F(" SlotConfig0E | SlotConfig0F | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j == 1) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x34) + { + Serial.print(F(" UseFlag00 | UpdateCount00 | UseFlag01 | UpdateCount01 | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j < 3) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x38) + { + Serial.print(F(" UseFlag02 | UpdateCount02 | UseFlag03 | UpdateCount03 | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j < 3) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x3C) + { + Serial.print(F(" UseFlag04 | UpdateCount04 | UseFlag05 | UpdateCount05 | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j < 3) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x40) + { + Serial.print(F(" UseFlag06 | UpdateCount06 | UseFlag07 | UpdateCount07 | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j < 3) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + else if (i == 0x44) + { + Serial.print(F(" LastKeyUse[0:3] | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + Serial.print(F(" ")); + } + Serial.println(); + } + else if (i == 0x48) + { + Serial.print(F(" LastKeyUse[4:7] | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + Serial.print(F(" ")); + } + Serial.println(); + } + else if (i == 0x4C) + { + Serial.print(F(" LastKeyUse[8:B] | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + Serial.print(F(" ")); + } + Serial.println(); + } + else if (i == 0x50) + { + Serial.print(F(" LastKeyUse[C:F] | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + Serial.print(F(" ")); + } + Serial.println(); + } + else if (i == 0x54) + { + Serial.print(F(" UserExtra | Selector | LockValue | LockConfig | ")); + for (int j=0; j<4; j++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+j] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+j], HEX); + if (j < 3) + { + Serial.print(F(" | ")); + } + else + { + Serial.print(F(" ")); + } + } + Serial.println(); + } + } +} + +void setup() +{ + uint8_t tx_buffer[SHA204_CMD_SIZE_MAX]; + uint8_t rx_buffer[SHA204_RSP_SIZE_MAX]; + uint8_t key[32]; + uint8_t ret_code; + uint8_t lockConfig = 0; + uint8_t lockValue = 0; + uint16_t crc; + Serial.begin(115200); + + Serial.println(F("ATSHA204 personalization sketch for MySensors usage.")); + Serial.println(F("----------------------------------------------------")); + + // Wake device before starting operations + ret_code = sha204.sha204c_wakeup(rx_buffer); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Failed to wake device. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + + // Output device revision on console + ret_code = sha204.sha204m_dev_rev(tx_buffer, rx_buffer); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Failed to determine device revision. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + else + { + Serial.print(F("Device revision: ")); + for (int i=0; i<4; i++) + { + if (rx_buffer[SHA204_BUFFER_POS_DATA+i] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[SHA204_BUFFER_POS_DATA+i], HEX); + } + Serial.println(); + } + + // Output serial number on console + ret_code = sha204.getSerialNumber(rx_buffer); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Failed to obtain device serial number. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + else + { + Serial.print(F("Device serial: ")); + for (int i=0; i<9; i++) + { + if (rx_buffer[i] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[i], HEX); + } + Serial.println(); + } + + // Read out lock config bits to determine if locking is possible + ret_code = sha204.sha204m_read(tx_buffer, rx_buffer, SHA204_ZONE_CONFIG, 0x15<<2); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Failed to determine device lock status. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + else + { + lockConfig = rx_buffer[SHA204_BUFFER_POS_DATA+3]; + lockValue = rx_buffer[SHA204_BUFFER_POS_DATA+2]; + } + + if (lockConfig != 0x00) + { + // Write config and get CRC for the updated config + crc = write_config_and_get_crc(); + + // List current configuration before attempting to lock + Serial.println(F("Chip configuration:")); + dump_configuration(); + +#ifdef LOCK_CONFIGURATION + // Purge serial input buffer + while (Serial.available()) + { + Serial.read(); + } + Serial.println(F("Send SPACE character now to lock the configuration...")); + + while (Serial.available() == 0); + if (Serial.read() == ' ') + { + Serial.println(F("Locking configuration...")); + + // Correct sequence, resync chip + ret_code = sha204.sha204c_resync(SHA204_RSP_SIZE_MAX, rx_buffer); + if (ret_code != SHA204_SUCCESS && ret_code != SHA204_RESYNC_WITH_WAKEUP) + { + Serial.print(F("Resync failed. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + + // Lock configuration zone + ret_code = sha204.sha204m_execute(SHA204_LOCK, SHA204_ZONE_CONFIG, + crc, 0, NULL, 0, NULL, 0, NULL, + LOCK_COUNT, tx_buffer, LOCK_RSP_SIZE, rx_buffer); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Configuration lock failed. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + else + { + Serial.println(F("Configuration locked.")); + + // Update lock flags after locking + ret_code = sha204.sha204m_read(tx_buffer, rx_buffer, SHA204_ZONE_CONFIG, 0x15<<2); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Failed to determine device lock status. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + else + { + lockConfig = rx_buffer[SHA204_BUFFER_POS_DATA+3]; + lockValue = rx_buffer[SHA204_BUFFER_POS_DATA+2]; + } + } + } + else + { + Serial.println(F("Unexpected answer. Skipping lock.")); + } +#else //LOCK_CONFIGURATION + Serial.println(F("Dry-run. Configuration not locked. Define LOCK_CONFIGURATION to lock for real.")); +#endif + } + else + { + Serial.println(F("Skipping configuration write and lock (configuration already locked).")); + Serial.println(F("Chip configuration:")); + dump_configuration(); + } + +#ifdef SKIP_KEY_STORAGE + Serial.println(F("Disable SKIP_KEY_STORAGE to store key.")); +#else +#ifdef USER_KEY_DATA + memcpy(key, user_key_data, 32); + Serial.print(F("Using this user supplied key: ")); +#else + // Retrieve random value to use as key + ret_code = sha204.sha204m_random(tx_buffer, rx_buffer, RANDOM_SEED_UPDATE); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Random key generation failed. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + else + { + memcpy(key, rx_buffer+SHA204_BUFFER_POS_DATA, 32); + } + if (lockConfig == 0x00) + { + Serial.println(F("Take note of this key, it will never be the shown again:")); + } + else + { + Serial.println(F("Key is not randomized (configuration not locked):")); + } +#endif + for (int i=0; i<32; i++) + { + if (key[i] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(key[i], HEX); + } + Serial.println(); + + // It will not be possible to write the key if the configuration zone is unlocked + if (lockConfig == 0x00) + { + // Write the key to the appropriate slot in the data zone + Serial.println(F("Writing key to slot 0...")); + write_key(key); + } + else + { + Serial.println(F("Skipping key storage (configuration not locked).")); + Serial.println(F("The configuration must be locked to be able to write a key.")); + } +#endif + + if (lockValue != 0x00) + { +#ifdef LOCK_DATA + while (Serial.available()) + { + Serial.read(); + } + Serial.println(F("Send SPACE character to lock data...")); + while (Serial.available() == 0); + if (Serial.read() == ' ') + { + // Correct sequence, resync chip + ret_code = sha204.sha204c_resync(SHA204_RSP_SIZE_MAX, rx_buffer); + if (ret_code != SHA204_SUCCESS && ret_code != SHA204_RESYNC_WITH_WAKEUP) + { + Serial.print(F("Resync failed. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + + // If configuration is unlocked, key is not updated. Locking data in this case will cause + // slot 0 to contain an unknown (or factory default) key, and this is in practically any + // usecase not the desired behaviour, so ask for additional confirmation in this case. + if (lockConfig != 0x00) + { + while (Serial.available()) + { + Serial.read(); + } + Serial.println(F("*** ATTENTION ***")); + Serial.println(F("Configuration is not locked. Are you ABSULOUTELY SURE you want to lock data?")); + Serial.println(F("Locking data at this stage will cause slot 0 to contain a factory default key")); + Serial.println(F("which cannot be change after locking is done. This is in practically any usecase")); + Serial.println(F("NOT the desired behavour. Send SPACE character now to lock data anyway...")); + while (Serial.available() == 0); + if (Serial.read() != ' ') + { + Serial.println(F("Unexpected answer. Skipping lock.")); + halt(); + } + } + + // Lock data zone + ret_code = sha204.sha204m_execute(SHA204_LOCK, SHA204_ZONE_DATA | LOCK_ZONE_NO_CRC, + 0x0000, 0, NULL, 0, NULL, 0, NULL, + LOCK_COUNT, tx_buffer, LOCK_RSP_SIZE, rx_buffer); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Data lock failed. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + else + { + Serial.println(F("Data locked.")); + + // Update lock flags after locking + ret_code = sha204.sha204m_read(tx_buffer, rx_buffer, SHA204_ZONE_CONFIG, 0x15<<2); + if (ret_code != SHA204_SUCCESS) + { + Serial.print(F("Failed to determine device lock status. Response: ")); Serial.println(ret_code, HEX); + halt(); + } + else + { + lockConfig = rx_buffer[SHA204_BUFFER_POS_DATA+3]; + lockValue = rx_buffer[SHA204_BUFFER_POS_DATA+2]; + } + } + } + else + { + Serial.println(F("Unexpected answer. Skipping lock.")); + } +#else //LOCK_DATA + Serial.println(F("Dry-run. Data not locked. Define LOCK_DATA to lock for real.")); +#endif + } + else + { + Serial.println(F("Skipping OTP/data zone lock (zone already locked).")); + } + + Serial.println(F("--------------------------------")); + Serial.println(F("Personalization is now complete.")); + Serial.print(F("Configuration is ")); + if (lockConfig == 0x00) + { + Serial.println("LOCKED"); + } + else + { + Serial.println("UNLOCKED"); + } + Serial.print(F("Data is ")); + if (lockValue == 0x00) + { + Serial.println("LOCKED"); + } + else + { + Serial.println("UNLOCKED"); + } +} + +void loop() +{ +} From f1f8aec324f754f4fe221c4d2b72196702eec3ca Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Sun, 11 Jan 2015 20:29:22 +0100 Subject: [PATCH 029/137] Change order of ethernet/radio intialization to avoid troubles. --- .../MySensors/examples/EthernetGateway/EthernetGateway.ino | 6 ++++-- libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 2c191f9..54e6252 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -101,8 +101,6 @@ void output(const char *fmt, ... ) { void setup() { - // Initialize gateway at maximum PA level, channel 70 and callback for write operations - gw.begin(incomingMessage, 0, true, 0); Ethernet.begin(mac, myIp); setupGateway(RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN, INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output); @@ -116,6 +114,10 @@ void setup() // give the Ethernet interface a second to initialize delay(1000); + + // Initialize gateway at maximum PA level, channel 70 and callback for write operations + gw.begin(incomingMessage, 0, true, 0); + // start listening for clients server.begin(); diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index 219b4e2..de61f13 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -145,8 +145,6 @@ void incomingMessage(const MyMessage &message) { void setup() { - // Initialize gateway at maximum PA level, channel 70 and callback for write operations - gw.begin(incomingMessage, 0, true, 0); Ethernet.begin(TCP_MAC, TCP_IP); @@ -177,6 +175,10 @@ void setup() // give the Ethernet interface a second to initialize delay(1000); + + // Initialize gateway at maximum PA level, channel 70 and callback for write operations + gw.begin(incomingMessage, 0, true, 0); + // start listening for clients server.begin(); From 7d37cd9aa5a3c6b70c442cb86d6763369f989b83 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Wed, 28 Jan 2015 21:25:19 +0100 Subject: [PATCH 030/137] MyDriver structure renamed to MyRFDriver The MyDriver scheme is radio specific, so it is renamed accordingly to permit other driver schemes to coexist with it without confusion. --- libraries/MySensors/MyConfig.h | 8 +++---- libraries/MySensors/MyDriver.cpp | 4 ---- libraries/MySensors/MyRFDriver.cpp | 4 ++++ .../MySensors/{MyDriver.h => MyRFDriver.h} | 10 ++++----- ...{MyDriverNRF24.cpp => MyRFDriverNRF24.cpp} | 20 ++++++++--------- .../{MyDriverNRF24.h => MyRFDriverNRF24.h} | 10 ++++----- .../{MyDriverRF69.cpp => MyRFDriverRF69.cpp} | 20 ++++++++--------- .../{MyDriverRF69.h => MyRFDriverRF69.h} | 12 +++++----- libraries/MySensors/MySensor.cpp | 22 +++++++++---------- libraries/MySensors/MySensor.h | 4 ++-- .../examples/EthernetGateway/GatewayUtil.h | 2 +- .../examples/SerialGateway/GatewayUtil.h | 2 +- 12 files changed, 59 insertions(+), 59 deletions(-) delete mode 100644 libraries/MySensors/MyDriver.cpp create mode 100644 libraries/MySensors/MyRFDriver.cpp rename libraries/MySensors/{MyDriver.h => MyRFDriver.h} (94%) rename libraries/MySensors/{MyDriverNRF24.cpp => MyRFDriverNRF24.cpp} (75%) rename libraries/MySensors/{MyDriverNRF24.h => MyRFDriverNRF24.h} (90%) rename libraries/MySensors/{MyDriverRF69.cpp => MyRFDriverRF69.cpp} (60%) rename libraries/MySensors/{MyDriverRF69.h => MyRFDriverRF69.h} (88%) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 3b7d3ed..4d0182a 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -19,13 +19,13 @@ #ifdef MYSENSORS_RF_NRF24 -#include "MyDriverNRF24.h" -typedef class MyDriverNRF24 MyDriverClass; +#include "MyRFDriverNRF24.h" +typedef class MyRFDriverNRF24 MyRFDriverClass; #endif #ifdef MYSENSORS_RF_RF69 -#include "MyDriverRF69.h" -typedef class MyDriverRF69 MyDriverClass; +#include "MyRFDriverRF69.h" +typedef class MyRFDriverRF69 MyRFDriverClass; #endif /*** diff --git a/libraries/MySensors/MyDriver.cpp b/libraries/MySensors/MyDriver.cpp deleted file mode 100644 index e592552..0000000 --- a/libraries/MySensors/MyDriver.cpp +++ /dev/null @@ -1,4 +0,0 @@ -#include "MyDriver.h" - -MyDriver::MyDriver() { -} diff --git a/libraries/MySensors/MyRFDriver.cpp b/libraries/MySensors/MyRFDriver.cpp new file mode 100644 index 0000000..cf669a0 --- /dev/null +++ b/libraries/MySensors/MyRFDriver.cpp @@ -0,0 +1,4 @@ +#include "MyRFDriver.h" + +MyRFDriver::MyRFDriver() { +} diff --git a/libraries/MySensors/MyDriver.h b/libraries/MySensors/MyRFDriver.h similarity index 94% rename from libraries/MySensors/MyDriver.h rename to libraries/MySensors/MyRFDriver.h index fe35f5f..8157af1 100644 --- a/libraries/MySensors/MyDriver.h +++ b/libraries/MySensors/MyRFDriver.h @@ -1,5 +1,5 @@ -#ifndef MyDriver_h -#define MyDriver_h +#ifndef MyRFDriver_h +#define MyRFDriver_h #include @@ -16,13 +16,13 @@ #define GATEWAY_ADDRESS ((uint8_t)0) #define BROADCAST_ADDRESS ((uint8_t)0xFF) -class MyDriver +class MyRFDriver { public: - // MyDriver constructor + // MyRFDriver constructor // different parameters would be needed depending on radio module (e.g. pins connected etc.) // keeping these parameters as #define's in MyConfig to streamline the driver interface - MyDriver(); + MyRFDriver(); // init() // different parameters would be needed depending on radio module (e.g. channel, power, crc, etc.) // keeping these parameters as #define's in MyConfig to streamline the driver interface diff --git a/libraries/MySensors/MyDriverNRF24.cpp b/libraries/MySensors/MyRFDriverNRF24.cpp similarity index 75% rename from libraries/MySensors/MyDriverNRF24.cpp rename to libraries/MySensors/MyRFDriverNRF24.cpp index a6b3ac1..adfabc8 100644 --- a/libraries/MySensors/MyDriverNRF24.cpp +++ b/libraries/MySensors/MyRFDriverNRF24.cpp @@ -1,11 +1,11 @@ -#include "MyDriver.h" -#include "MyDriverNRF24.h" +#include "MyRFDriver.h" +#include "MyRFDriverNRF24.h" -MyDriverNRF24::MyDriverNRF24() : MyDriver() { +MyRFDriverNRF24::MyRFDriverNRF24() : MyRFDriver() { rf24 = new RF24(RF24_CE_PIN, RF24_CS_PIN); } -void MyDriverNRF24::init() { +void MyRFDriverNRF24::init() { // Start up the radio library rf24->begin(); @@ -27,18 +27,18 @@ void MyDriverNRF24::init() { rf24->openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); } -void MyDriverNRF24::setAddress(uint8_t address) { +void MyRFDriverNRF24::setAddress(uint8_t address) { _address = address; rf24->openReadingPipe(WRITE_PIPE, TO_ADDR(address)); rf24->openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(address)); rf24->startListening(); } -uint8_t MyDriverNRF24::getAddress() { +uint8_t MyRFDriverNRF24::getAddress() { return _address; } -bool MyDriverNRF24::send(uint8_t to, const void* data, uint8_t len) { +bool MyRFDriverNRF24::send(uint8_t to, const void* data, uint8_t len) { // Make sure radio has powered up rf24->powerUp(); rf24->stopListening(); @@ -48,7 +48,7 @@ bool MyDriverNRF24::send(uint8_t to, const void* data, uint8_t len) { return ok; } -bool MyDriverNRF24::available(uint8_t *to) { +bool MyRFDriverNRF24::available(uint8_t *to) { uint8_t pipe = 255; boolean avail = rf24->available(&pipe); if (pipe == CURRENT_NODE_PIPE) @@ -58,11 +58,11 @@ bool MyDriverNRF24::available(uint8_t *to) { return (rf24->available() && pipe < 6); } -uint8_t MyDriverNRF24::receive(void* data) { +uint8_t MyRFDriverNRF24::receive(void* data) { uint8_t len = rf24->getDynamicPayloadSize(); rf24->read(data, len); } -void MyDriverNRF24::powerDown() { +void MyRFDriverNRF24::powerDown() { rf24->powerDown(); } diff --git a/libraries/MySensors/MyDriverNRF24.h b/libraries/MySensors/MyRFDriverNRF24.h similarity index 90% rename from libraries/MySensors/MyDriverNRF24.h rename to libraries/MySensors/MyRFDriverNRF24.h index 8ad9b4d..66a78fe 100644 --- a/libraries/MySensors/MyDriverNRF24.h +++ b/libraries/MySensors/MyRFDriverNRF24.h @@ -1,8 +1,8 @@ -#ifndef MyCommDriver_h -#define MyCommDriver_h +#ifndef MyRFDriverNRF24_h +#define MyRFDriverNRF24_h #include "MyConfig.h" -#include "MyDriver.h" +#include "MyRFDriver.h" #include #include "utility/RF24.h" #include "utility/RF24_config.h" @@ -37,10 +37,10 @@ #define CURRENT_NODE_PIPE ((uint8_t)1) #define BROADCAST_PIPE ((uint8_t)2) -class MyDriverNRF24 : public MyDriver +class MyRFDriverNRF24 : public MyRFDriver { public: - MyDriverNRF24(); + MyRFDriverNRF24(); void init(); void setAddress(uint8_t address); uint8_t getAddress(); diff --git a/libraries/MySensors/MyDriverRF69.cpp b/libraries/MySensors/MyRFDriverRF69.cpp similarity index 60% rename from libraries/MySensors/MyDriverRF69.cpp rename to libraries/MySensors/MyRFDriverRF69.cpp index 2363da7..360671d 100644 --- a/libraries/MySensors/MyDriverRF69.cpp +++ b/libraries/MySensors/MyRFDriverRF69.cpp @@ -1,11 +1,11 @@ -#include "MyDriver.h" -#include "MyDriverRF69.h" +#include "MyRFDriver.h" +#include "MyRFDriverRF69.h" -MyDriverRF69::MyDriverRF69() : MyDriver() { +MyRFDriverRF69::MyRFDriverRF69() : MyRFDriver() { radio = new RFM69(); } -void MyDriverRF69::init() { +void MyRFDriverRF69::init() { // Start up the radio library radio->initialize(FREQUENCY,_address,NETWORKID); #ifdef IS_RFM69HW @@ -15,25 +15,25 @@ void MyDriverRF69::init() { } -void MyDriverRF69::setAddress(uint8_t address) { +void MyRFDriverRF69::setAddress(uint8_t address) { _address = address; radio->setAddress(address); } -uint8_t MyDriverRF69::getAddress() { +uint8_t MyRFDriverRF69::getAddress() { return _address; } -bool MyDriverRF69::send(uint8_t to, const void* data, uint8_t len) { +bool MyRFDriverRF69::send(uint8_t to, const void* data, uint8_t len) { // Make sure radio has powered up return radio->sendWithRetry(to,data,len); } -bool MyDriverRF69::available(uint8_t *to) { +bool MyRFDriverRF69::available(uint8_t *to) { return radio->receiveDone(); } -uint8_t MyDriverRF69::receive(void* data) { +uint8_t MyRFDriverRF69::receive(void* data) { // for (byte i = 0; i < radio->DATALEN; i++){ // data[i]= (void)radio->DATA[i]; // } @@ -44,6 +44,6 @@ uint8_t MyDriverRF69::receive(void* data) { } } -void MyDriverRF69::powerDown() { +void MyRFDriverRF69::powerDown() { radio->sleep(); } diff --git a/libraries/MySensors/MyDriverRF69.h b/libraries/MySensors/MyRFDriverRF69.h similarity index 88% rename from libraries/MySensors/MyDriverRF69.h rename to libraries/MySensors/MyRFDriverRF69.h index 6b14772..256cc4d 100644 --- a/libraries/MySensors/MyDriverRF69.h +++ b/libraries/MySensors/MyRFDriverRF69.h @@ -1,8 +1,8 @@ -#ifndef MyCommDriver_h -#define MyCommDriver_h +#ifndef MyRFDriverRF69_h +#define MyRFDriverRF69_h #include "MyConfig.h" -#include "MyDriver.h" +#include "MyRFDriver.h" #include #include "utility/RFM69.h" #include @@ -25,10 +25,10 @@ #define FLASH_SS 8 // and FLASH SS on D8 #endif -class MyDriverRF69 : public MyDriver +class MyRFDriverRF69 : public MyRFDriver { public: - MyDriverRF69(); + MyRFDriverRF69(); void init(); void setAddress(uint8_t address); uint8_t getAddress(); @@ -37,7 +37,7 @@ public: uint8_t receive(void* data); void powerDown(); private: - RFM69 *radio = NULL; + RFM69 *radio; uint8_t _address; }; diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index c56da76..21ac36c 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -34,7 +34,7 @@ static inline bool isValidDistance( const uint8_t distance ) { } MySensor::MySensor() { - driver = (MyDriver*) new MyDriverClass(); + radio = (MyRFDriver*) new MyRFDriverClass(); } @@ -89,7 +89,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b } // Open reading pipe for messages directed to this node (set write pipe to same) - driver->setAddress(nc.nodeId); + radio->setAddress(nc.nodeId); // Send presentation for this radio node (attach present(NODE_SENSOR_ID, repeaterMode? S_ARDUINO_REPEATER_NODE : S_ARDUINO_NODE); @@ -105,7 +105,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b void MySensor::setupRadio() { failedTransmissions = 0; - driver->init(); + radio->init(); } void MySensor::setupRepeaterMode(){ @@ -124,7 +124,7 @@ ControllerConfig MySensor::getConfig() { void MySensor::requestNodeId() { debug(PSTR("req node id\n")); - driver->setAddress(nc.nodeId); + radio->setAddress(nc.nodeId); sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_ID_REQUEST, false).set("")); waitForReply(); } @@ -202,7 +202,7 @@ boolean MySensor::sendWrite(uint8_t next, MyMessage &message, const bool allowFi uint8_t length = mGetLength(message); message.last = nc.nodeId; mSetVersion(message, PROTOCOL_VERSION); - bool ok = driver->send(next, &message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length)); + bool ok = radio->send(next, &message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length)); debug(PSTR("send: %d-%d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d,st=%s:%s\n"), message.sender,message.last, next, message.destination, message.sensor, mGetCommand(message), message.type, @@ -264,10 +264,10 @@ void MySensor::requestTime(void (* _timeCallback)(unsigned long)) { boolean MySensor::process() { uint8_t to = 0; - if (!driver->available(&to)) + if (!radio->available(&to)) return false; - uint8_t len = driver->receive((uint8_t *)&msg); + uint8_t len = radio->receive((uint8_t *)&msg); // Add string termination, good if we later would want to print it. msg.data[mGetLength(msg)] = '\0'; @@ -351,7 +351,7 @@ boolean MySensor::process() { debug(PSTR("full\n")); while (1); // Wait here. Nothing else we can do... } else { - driver->setAddress(nc.nodeId); + radio->setAddress(nc.nodeId); eeprom_write_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, nc.nodeId); } debug(PSTR("id=%d\n"), nc.nodeId); @@ -482,7 +482,7 @@ void MySensor::internalSleep(unsigned long ms) { void MySensor::sleep(unsigned long ms) { // Let serial prints finish (debug, log etc) Serial.flush(); - driver->powerDown(); + radio->powerDown(); pinIntTrigger = 0; internalSleep(ms); } @@ -491,7 +491,7 @@ bool MySensor::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { // Let serial prints finish (debug, log etc) bool pinTriggeredWakeup = true; Serial.flush(); - driver->powerDown(); + radio->powerDown(); attachInterrupt(interrupt, wakeUp, mode); if (ms>0) { pinIntTrigger = 0; @@ -510,7 +510,7 @@ bool MySensor::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { int8_t MySensor::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) { int8_t retVal = 1; Serial.flush(); // Let serial prints finish (debug, log etc) - driver->powerDown(); + radio->powerDown(); attachInterrupt(interrupt1, wakeUp, mode1); attachInterrupt(interrupt2, wakeUp2, mode2); if (ms>0) { diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 5cb6d5e..8aafaa0 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -13,7 +13,7 @@ #define MySensor_h #include "Version.h" // Auto generated by bot -#include "MyDriver.h" +#include "MyRFDriver.h" #include "MyConfig.h" #include "MyMessage.h" #include @@ -232,7 +232,7 @@ class MySensor MyMessage msg; // Buffer for incoming messages. MyMessage ack; // Buffer for ack messages. - MyDriver *driver; + MyRFDriver *radio; void setupRepeaterMode(); void setupRadio(); diff --git a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h index 5ce7be4..b5ac2ba 100644 --- a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h @@ -1,7 +1,7 @@ #ifndef __GATEWAYUTIL_H__ #define __GATEWAYUTIL_H__ -#include +#include #ifdef ARDUINO diff --git a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h index 5ce7be4..b5ac2ba 100644 --- a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h @@ -1,7 +1,7 @@ #ifndef __GATEWAYUTIL_H__ #define __GATEWAYUTIL_H__ -#include +#include #ifdef ARDUINO From 615da4509ced6fb15ca37ae84099efe6ac94adb1 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 3 Feb 2015 23:58:38 +0100 Subject: [PATCH 031/137] Fix ack problems RF24 --- libraries/MySensors/MyRFDriverNRF24.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MyRFDriverNRF24.cpp b/libraries/MySensors/MyRFDriverNRF24.cpp index adfabc8..faaf73d 100644 --- a/libraries/MySensors/MyRFDriverNRF24.cpp +++ b/libraries/MySensors/MyRFDriverNRF24.cpp @@ -15,13 +15,13 @@ void MyRFDriverNRF24::init() { } rf24->setAutoAck(1); rf24->setAutoAck(BROADCAST_PIPE,false); // Turn off auto ack for broadcast + rf24->enableAckPayload(); rf24->setChannel(RF24_CHANNEL); rf24->setPALevel(RF24_PA_LEVEL); rf24->setDataRate(RF24_DATARATE); rf24->setRetries(5,15); rf24->setCRCLength(RF24_CRC_16); rf24->enableDynamicPayloads(); - rf24->enableDynamicAck(); // All nodes listen to broadcast pipe (for FIND_PARENT_RESPONSE messages) rf24->openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); From 83be24d2bead9482b7c4223f851378501278f6cf Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 4 Feb 2015 22:04:32 +0100 Subject: [PATCH 032/137] Return length from receive() --- libraries/MySensors/MyRFDriverNRF24.cpp | 1 + libraries/MySensors/MyRFDriverRF69.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/libraries/MySensors/MyRFDriverNRF24.cpp b/libraries/MySensors/MyRFDriverNRF24.cpp index faaf73d..1667fc6 100644 --- a/libraries/MySensors/MyRFDriverNRF24.cpp +++ b/libraries/MySensors/MyRFDriverNRF24.cpp @@ -61,6 +61,7 @@ bool MyRFDriverNRF24::available(uint8_t *to) { uint8_t MyRFDriverNRF24::receive(void* data) { uint8_t len = rf24->getDynamicPayloadSize(); rf24->read(data, len); + return len; } void MyRFDriverNRF24::powerDown() { diff --git a/libraries/MySensors/MyRFDriverRF69.cpp b/libraries/MySensors/MyRFDriverRF69.cpp index 360671d..57b9f8d 100644 --- a/libraries/MySensors/MyRFDriverRF69.cpp +++ b/libraries/MySensors/MyRFDriverRF69.cpp @@ -42,6 +42,7 @@ uint8_t MyRFDriverRF69::receive(void* data) { { radio->sendACK(); } + return radio->DATALEN; } void MyRFDriverRF69::powerDown() { From 17a680f1de54867115af92b2e25ab95fb48f3cf1 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 11 Feb 2015 00:07:19 +0100 Subject: [PATCH 033/137] Fix broadcast check for RF69 --- libraries/MySensors/MyRFDriverRF69.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libraries/MySensors/MyRFDriverRF69.cpp b/libraries/MySensors/MyRFDriverRF69.cpp index 57b9f8d..80e8874 100644 --- a/libraries/MySensors/MyRFDriverRF69.cpp +++ b/libraries/MySensors/MyRFDriverRF69.cpp @@ -30,6 +30,10 @@ bool MyRFDriverRF69::send(uint8_t to, const void* data, uint8_t len) { } bool MyRFDriverRF69::available(uint8_t *to) { + if (radio->TARGETID == BROADCAST_ADDRESS) + *to = BROADCAST_ADDRESS; + else + *to = _address; return radio->receiveDone(); } From c8883c61e67447dccb3c2021b3567d46161e118d Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 12 Feb 2015 21:58:16 +0100 Subject: [PATCH 034/137] Request parent missing in setup() --- libraries/MySensors/MySensor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index b24ef75..50445a4 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -74,8 +74,8 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b // If the current node is also repeater, be aware of this. nc.distance = 1; } else if (!isValidParent(nc.parentNodeId)) { - // Auto find parent, but parent in eeprom is invalid. Force parent search on first transmit. - nc.distance = DISTANCE_INVALID; + // Auto find parent, but parent in eeprom is invalid. Try find one. + findParentNode(); } if ( (_nodeId != AUTO) && (nc.nodeId != _nodeId) ) { From f3c60a068f06a913b8953c4d70210641d642788b Mon Sep 17 00:00:00 2001 From: Marcelo Aquino Date: Fri, 13 Feb 2015 02:01:18 -0200 Subject: [PATCH 035/137] process() uses sendRoute() for routing decisions To keep routing decisions in one place, and avoid rewriting the same code to add failedTransmissions count to process() --- libraries/MySensors/MySensor.cpp | 127 +++++++++++++++---------------- 1 file changed, 63 insertions(+), 64 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index d34aa61..6636214 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -125,7 +125,8 @@ ControllerConfig MySensor::getConfig() { void MySensor::requestNodeId() { debug(PSTR("req node id\n")); radio->setAddress(nc.nodeId); - sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_ID_REQUEST, false).set("")); + build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_ID_REQUEST, false).set(""); + sendWrite(nc.parentNodeId, msg); wait(2000); } @@ -160,49 +161,82 @@ void MySensor::findParentNode() { } boolean MySensor::sendRoute(MyMessage &message) { - // Make sure to process any incoming messages before sending (could this end up in recursive loop?) - // process(); - bool isInternal = mGetCommand(message) == C_INTERNAL; + uint8_t sender = message.sender; + uint8_t dest = message.destination; + uint8_t last = message.last; + bool ok; + + // If we still don't have any parent id, re-request and skip this message. + if (nc.parentNodeId == AUTO) { + findParentNode(); + return false; + } // If we still don't have any node id, re-request and skip this message. - if (nc.nodeId == AUTO && !(isInternal && message.type == I_ID_REQUEST)) { + if (nc.nodeId == AUTO) { requestNodeId(); return false; } - if (repeaterMode) { - uint8_t dest = message.destination; + if (dest == GATEWAY_ADDRESS || !repeaterMode) { + // If destination is the gateway or if we aren't a repeater, let + // our parent take care of the message + ok = sendWrite(nc.parentNodeId, message); + } else { + // Relay the message uint8_t route = getChildRoute(dest); - if (route>GATEWAY_ADDRESS && route GATEWAY_ADDRESS && route < BROADCAST_ADDRESS) { + // This message should be forwarded to a child node. If we send message + // to this nodes pipe then all children will receive it because the are + // all listening to this nodes pipe. + // + // +----B + // -A + // +----C------D + // + // We're node C, Message comes from A and has destination D + // // Message destination is not gateway and is in routing table for this node. // Send it downstream return sendWrite(route, message); - } else if (isInternal && message.type == I_ID_RESPONSE && dest==BROADCAST_ADDRESS) { + } else if (sender == GATEWAY_ADDRESS && dest == BROADCAST_ADDRESS) { // Node has not yet received any id. We need to send it // by doing a broadcast sending, return sendWrite(BROADCAST_ADDRESS, message); + } else if (isGateway) { + // Destination isn't in our routing table and isn't a broadcast address + // Nothing to do here + return false; + } else { + // A message comes from a child node and we have no + // route for it. + // + // +----B + // -A + // +----C------D <-- Message comes from D + // + // We're node C + // + // Message should be passed to node A (this nodes relay) + + // This message should be routed back towards sensor net gateway + ok = sendWrite(nc.parentNodeId, message); + // Add this child to our "routing table" if it not already exist + addChildRoute(sender, last); } } - if (!isGateway) { - // Should be routed back to gateway. - bool ok = sendWrite(nc.parentNodeId, message); - - if (!ok) { - // Failure when sending to parent node. The parent node might be down and we - // need to find another route to gateway. - if (autoFindParent && failedTransmissions > SEARCH_FAILURES) { - findParentNode(); - } else { - failedTransmissions++; - } - } else { - failedTransmissions = 0; + if (!ok) { + // Failure when sending to parent node. The parent node might be down and we + // need to find another route to gateway. + failedTransmissions++; + if (autoFindParent && failedTransmissions > SEARCH_FAILURES) { + findParentNode(); } - return ok; + } else { + failedTransmissions = 0; } - return false; + return ok; } boolean MySensor::sendWrite(uint8_t to, MyMessage &message) { @@ -369,10 +403,10 @@ boolean MySensor::process() { // Return true if message was addressed for this node... return true; } else if (repeaterMode && nc.nodeId != AUTO) { - // Relaying nodes should answer only after set an id + // If this node have an id, relay the message if (command == C_INTERNAL && type == I_FIND_PARENT) { - if (nc.distance == 255) { + if (nc.distance == DISTANCE_INVALID) { findParentNode(); } else if (sender != nc.parentNodeId) { // Relaying nodes should always answer ping messages @@ -383,42 +417,7 @@ boolean MySensor::process() { } } else if (to == nc.nodeId) { // We should try to relay this message to another node - - uint8_t route = getChildRoute(msg.destination); - if (route>0 && route<255) { - // This message should be forwarded to a child node. If we send message - // to this nodes pipe then all children will receive it because the are - // all listening to this nodes pipe. - // - // +----B - // -A - // +----C------D - // - // We're node C, Message comes from A and has destination D - // - // lookup route in table and send message there - sendWrite(route, msg); - } else if (sender == GATEWAY_ADDRESS && destination == BROADCAST_ADDRESS) { - // A net gateway reply to a message previously sent by us from a 255 node - // We should broadcast this back to the node - sendWrite(BROADCAST_ADDRESS, msg); - } else { - // A message comes from a child node and we have no - // route for it. - // - // +----B - // -A - // +----C------D <-- Message comes from D - // - // We're node C - // - // Message should be passed to node A (this nodes relay) - - // This message should be routed back towards sensor net gateway - sendWrite(nc.parentNodeId, msg); - // Add this child to our "routing table" if it not already exist - addChildRoute(sender, last); - } + sendRoute(msg); } } return false; From 4d3fc96ebfdd25f40c48e18e52e2ac96b7afcf22 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Mon, 16 Feb 2015 22:21:22 +0100 Subject: [PATCH 036/137] ATSHA204 personalization sketch updated New default pin is A3. New option to skip UART confirmation: SKIP_UART_CONFIRMATION This option prohibits the possibility to auto-generate key as there will probably not be a way to show the generated key to the user. More copy+paste friendly serial output of the generated key for insertion into personalization sketch. --- .../sha204_personalizer.ino | 41 +++++++++++++++---- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/libraries/sha204/examples/sha204_personalizer/sha204_personalizer.ino b/libraries/sha204/examples/sha204_personalizer/sha204_personalizer.ino index 771d024..a39ceeb 100644 --- a/libraries/sha204/examples/sha204_personalizer/sha204_personalizer.ino +++ b/libraries/sha204/examples/sha204_personalizer/sha204_personalizer.ino @@ -15,14 +15,15 @@ By default, no locking is performed. User have to manually enable the flags that turn on the locking. Furthermore, user have to send a SPACE character on serial - console when prompted to do any locking. - Default settings use ATSHA204 on pin 7. + console when prompted to do any locking. On boards that does not provide UART + input it is possible to configure the sketch to skip this confirmation. + Default settings use ATSHA204 on pin 17 (A3). */ #include #include // The pin the ATSHA204 is connected on -#define ATSHA204_PIN 7 +#define ATSHA204_PIN 17 // A3 // Uncomment this to enable locking the configuration zone. // *** BE AWARE THAT THIS PREVENTS ANY FUTURE CONFIGURATION CHANGE TO THE CHIP *** @@ -44,11 +45,24 @@ // Uncomment this to skip key generation and use 'user_key_data' as key instead. //#define USER_KEY_DATA +// Uncomment this for boards that lack UART +// IMPORTANT: No confirmation will be required for locking any zones with this +// configuration! +// Also, key generation is not permitted in this mode as there is no way of +// presenting the generated key. +//#define SKIP_UART_CONFIRMATION + +#if defined(SKIP_UART_CONFIRMATION) && !defined(USER_KEY_DATA) +#error You have to define USER_KEY_DATA for boards that does not have UART +#endif + #ifdef USER_KEY_DATA -const uint8_t user_key_data[32] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +const uint8_t user_key_data[32] = { +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +}; #endif const int sha204Pin = ATSHA204_PIN; @@ -727,6 +741,7 @@ void setup() #ifdef LOCK_CONFIGURATION // Purge serial input buffer +#ifndef SKIP_UART_CONFIRMATION while (Serial.available()) { Serial.read(); @@ -735,6 +750,7 @@ void setup() while (Serial.available() == 0); if (Serial.read() == ' ') +#endif //not SKIP_UART_CONFIRMATION { Serial.println(F("Locking configuration...")); @@ -773,10 +789,12 @@ void setup() } } } +#ifndef SKIP_UART_CONFIRMATION else { Serial.println(F("Unexpected answer. Skipping lock.")); } +#endif //not SKIP_UART_CONFIRMATION #else //LOCK_CONFIGURATION Serial.println(F("Dry-run. Configuration not locked. Define LOCK_CONFIGURATION to lock for real.")); #endif @@ -793,7 +811,7 @@ void setup() #else #ifdef USER_KEY_DATA memcpy(key, user_key_data, 32); - Serial.print(F("Using this user supplied key: ")); + Serial.println(F("Using this user supplied key:")); #else // Retrieve random value to use as key ret_code = sha204.sha204m_random(tx_buffer, rx_buffer, RANDOM_SEED_UPDATE); @@ -817,11 +835,14 @@ void setup() #endif for (int i=0; i<32; i++) { + Serial.print("0x"); if (key[i] < 0x10) { Serial.print('0'); // Because Serial.print does not 0-pad HEX } Serial.print(key[i], HEX); + if (i < 31) Serial.print(','); + if (!((i+1) % 8)) Serial.println(); } Serial.println(); @@ -842,6 +863,7 @@ void setup() if (lockValue != 0x00) { #ifdef LOCK_DATA +#ifndef SKIP_UART_CONFIRMATION while (Serial.available()) { Serial.read(); @@ -849,6 +871,7 @@ void setup() Serial.println(F("Send SPACE character to lock data...")); while (Serial.available() == 0); if (Serial.read() == ' ') +#endif //not SKIP_UART_CONFIRMATION { // Correct sequence, resync chip ret_code = sha204.sha204c_resync(SHA204_RSP_SIZE_MAX, rx_buffer); @@ -907,10 +930,12 @@ void setup() } } } +#ifndef SKIP_UART_CONFIRMATION else { Serial.println(F("Unexpected answer. Skipping lock.")); } +#endif //not SKIP_UART_CONFIRMATION #else //LOCK_DATA Serial.println(F("Dry-run. Data not locked. Define LOCK_DATA to lock for real.")); #endif From 93a23442e18517e5b03d5493ea98d00def84210d Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 17 Feb 2015 14:31:52 +0100 Subject: [PATCH 037/137] Add V_RGB, V_RGBW payload types and S_COLOR device type. --- libraries/MySensors/MyMessage.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index 643bdb2..a46fbee 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -39,7 +39,7 @@ typedef enum { V_IMPEDANCE, V_ARMED, V_TRIPPED, V_WATT, V_KWH, V_SCENE_ON, V_SCENE_OFF, V_HEATER, V_HEATER_SW, V_LIGHT_LEVEL, V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, V_UP, V_DOWN, V_STOP, V_IR_SEND, V_IR_RECEIVE, V_FLOW, V_VOLUME, V_LOCK_STATUS, - V_DUST_LEVEL, V_VOLTAGE, V_CURRENT + V_DUST_LEVEL, V_VOLTAGE, V_CURRENT, V_RGB, V_RGBW } mysensor_data; // Type of internal messages (for internal messages) @@ -55,7 +55,7 @@ typedef enum { S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, - S_SCENE_CONTROLLER + S_SCENE_CONTROLLER,S_COLOR } mysensor_sensor; // Type of data stream (for streamed message) From 60d6c4fc3cc8c13e9f365e7534e2ee886a21c248 Mon Sep 17 00:00:00 2001 From: Marcelo Aquino Date: Tue, 17 Feb 2015 17:24:51 -0200 Subject: [PATCH 038/137] add MYSENSORS_MQTT_GATEWAY definition --- libraries/MySensors/MyConfig.h | 3 ++- libraries/MySensors/MyRFDriverNRF24.h | 2 +- .../MySensors/examples/EthernetGateway/EthernetGateway.ino | 4 ++-- libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino | 4 ++-- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index d9cb7c2..96f2253 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -8,7 +8,8 @@ // pick ONE of these - other board layouts can be easily added this way #define MYSENSORS_SENSOR //#define MYSENSORS_SERIAL_GATEWAY -//#define MYSENSORS_ETHERNET_MQTT_GATEWAY +//#define MYSENSORS_ETHERNET_GATEWAY +//#define MYSENSORS_MQTT_GATEWAY // Choose radio type by enabling one of the following #define MYSENSORS_RF_NRF24 diff --git a/libraries/MySensors/MyRFDriverNRF24.h b/libraries/MySensors/MyRFDriverNRF24.h index 66a78fe..267b19c 100644 --- a/libraries/MySensors/MyRFDriverNRF24.h +++ b/libraries/MySensors/MyRFDriverNRF24.h @@ -21,7 +21,7 @@ #define RF24_PA_LEVEL RF24_PA_LOW #endif -#ifdef MYSENSORS_ETHERNET_MQTT_GATEWAY +#if defined(MYSENSORS_ETHERNET_GATEWAY) || defined(MYSENSORS_MQTT_GATEWAY) #define RF24_CE_PIN 5 #define RF24_CS_PIN 6 #define RF24_PA_LEVEL RF24_PA_LOW diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 143a6fe..f0f941c 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -48,8 +48,8 @@ #include #include "GatewayUtil.h" -#ifndef MYSENSORS_ETHERNET_MQTT_GATEWAY -#error Please switch to MYSENSORS_ETHERNET_MQTT_GATEWAY in MyConfig.h +#ifndef MYSENSORS_ETHERNET_GATEWAY +#error Please switch to MYSENSORS_ETHERNET_GATEWAY in MyConfig.h #endif // Use this if you have attached a Ethernet ENC28J60 shields diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index de61f13..a9a497d 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -62,8 +62,8 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway #include #include "MyMQTT.h" -#ifndef MYSENSORS_ETHERNET_MQTT_GATEWAY -#error Please switch to MYSENSORS_ETHERNET_MQTT_GATEWAY in MyConfig.h +#ifndef MYSENSORS_MQTT_GATEWAY +#error Please switch to MYSENSORS_MQTT_GATEWAY in MyConfig.h #endif #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled From 8b6463608a0eb8d0ddea2693563caa7daff65bda Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 17 Feb 2015 22:28:47 +0100 Subject: [PATCH 039/137] Fix merge error --- libraries/MySensors/MySensor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 6636214..7c8bff6 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -413,7 +413,7 @@ boolean MySensor::process() { // Wait a random delay of 0-2 seconds to minimize collision // between ping ack messages from other relaying nodes delay(millis() & 0x3ff); - sendWrite(BROADCAST_ADDRESS, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance)); + sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance)); } } else if (to == nc.nodeId) { // We should try to relay this message to another node From 9f337e3cae654fb95a2a1563f7190283fa80bd76 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Thu, 5 Feb 2015 22:49:05 +0100 Subject: [PATCH 040/137] Message header updates for signing support One bit in the protocol version field is converted to a sign indicator. '1' means the message carries a signature in the unused part of the payload data buffer. Three new internal message types have been defined: * I_REQUEST_SIGNING carries a boolean and is used to exchange signing requirement information between nodes. If the I_REQUEST_SIGNING carries 'true' the receiver is informed that the sender require properly signed messages in order to be able to accept the messages. * I_GET_NONCE is passed from sender to a receiver that require signing tellig it to submit a cryptographic 'nonce' that the sender needs in order to be able to sign the message it intend to send. The I_GET_NONCE carries no payload. * I_GET_NONCE_RESPONSE is sent by the receiver of a signed message in response to I_GET_NONCE. The first byte of the payload is a signing identifier informing the sender of the signed message about the type of signature the receiver is expecting. --- libraries/MySensors/MyMessage.h | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index a46fbee..fcc0540 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -47,7 +47,7 @@ typedef enum { I_BATTERY_LEVEL, I_TIME, I_VERSION, I_ID_REQUEST, I_ID_RESPONSE, I_INCLUSION_MODE, I_CONFIG, I_FIND_PARENT, I_FIND_PARENT_RESPONSE, I_LOG_MESSAGE, I_CHILDREN, I_SKETCH_NAME, I_SKETCH_VERSION, - I_REBOOT, I_GATEWAY_READY + I_REBOOT, I_GATEWAY_READY, I_REQUEST_SIGNING, I_GET_NONCE, I_GET_NONCE_RESPONSE } mysensor_internal; // Type of sensor (for presentation message) @@ -84,8 +84,11 @@ typedef enum { #define BF_SET(y, x, start, len) ( y= ((y) &~ BF_MASK(start, len)) | BF_PREP(x, start, len) ) // Getters/setters for special bit fields in header -#define mSetVersion(_msg,_version) BF_SET(_msg.version_length, _version, 0, 3) -#define mGetVersion(_msg) BF_GET(_msg.version_length, 0, 3) +#define mSetVersion(_msg,_version) BF_SET(_msg.version_length, _version, 0, 2) +#define mGetVersion(_msg) BF_GET(_msg.version_length, 0, 2) + +#define mSetSigned(_msg,_signed) BF_SET(_msg.version_length, _signed, 2, 1) +#define mGetSigned(_msg) BF_GET(_msg.version_length, 2, 1) #define mSetLength(_msg,_length) BF_SET(_msg.version_length, _length, 3, 5) #define mGetLength(_msg) BF_GET(_msg.version_length, 3, 5) @@ -179,7 +182,8 @@ struct uint8_t sender; // 8 bit - Id of sender node (origin) uint8_t destination; // 8 bit - Id of destination node - uint8_t version_length; // 3 bit - Protocol version + uint8_t version_length; // 2 bit - Protocol version + // 1 bit - Signed flag // 5 bit - Length of payload uint8_t command_ack_payload; // 3 bit - Command type // 1 bit - Request an ack - Indicator that receiver should send an ack back. From c2a75d064e05e841ca386d1318a275cd658af882 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 7 Feb 2015 00:19:13 +0100 Subject: [PATCH 041/137] Signing driver framework The signing driver framework resembles the radio driver framework in the sense that it relies on MyConfig.h for driver specific settings. This allows the constructor to be clean and the API less likely to need change. The API is designed with function pairs for sender and receiver of a signed message. The sender of a signed message uses putNonce() and signMsg() and the receiver of a signed message uses getNonce() and verifyMsg(). In addition, receiver is expected to call checkTimer() at regular intervals to make sure the message session does not time out. The program flow is that the sender transmit, after determining that the message needs signing, a request to the receiver for a nonce (I_GET_NONCE). The receiver calls getNonce() to obtain a nonce and transmits the nonce back to the sender (I_GET_NONCE_RESPONSE). The sender stores the received nonce in the driver with putNonce() and then calls signMsg() to sign the message to be transmitted. The receiver then calls verifyMsg() to authenticate the signed message using the nonce transmitted earlier. The flow is described below: ---------------- -------- ---------- ------------------ |senders driver| |sender| |receiver| |receivers driver| ---------------- -------- ---------- ------------------ | | I_GET_NONCE | getNonce() | | |------------------->|------------->| | | | | | setNonce() |I_GET_NONCE_RESPONSE| | |<-----------|<-------------------|<-------------| | signMsg() | | | |<-----------| | verifyMsg() | |----------->|------------------->|------------->| | | | OK / not OK | | | |<-------------| It is expected that all signing schemes is built upon this principle. --- libraries/MySensors/MySigningDriver.cpp | 4 ++ libraries/MySensors/MySigningDriver.h | 60 +++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 libraries/MySensors/MySigningDriver.cpp create mode 100644 libraries/MySensors/MySigningDriver.h diff --git a/libraries/MySensors/MySigningDriver.cpp b/libraries/MySensors/MySigningDriver.cpp new file mode 100644 index 0000000..b109a3f --- /dev/null +++ b/libraries/MySensors/MySigningDriver.cpp @@ -0,0 +1,4 @@ +#include "MySigningDriver.h" + +MySigningDriver::MySigningDriver() { +} diff --git a/libraries/MySensors/MySigningDriver.h b/libraries/MySensors/MySigningDriver.h new file mode 100644 index 0000000..28a75ea --- /dev/null +++ b/libraries/MySensors/MySigningDriver.h @@ -0,0 +1,60 @@ +/* + The MySigning driver provides a generic API for various signing backends to offer + signing of MySensors messages. + + Created by Patrick "Anticimex" Fallberg +*/ +#ifndef MySigningDriver_h +#define MySigningDriver_h + +#include +#include "MyMessage.h" + +class MySigningDriver +{ +public: + // MySigningDriver constructor. + // Different parameters would be needed depending on signing backend (e.g. pins connected etc.). + // Keeping these parameters as #define's in MyConfig to streamline the driver interface. + MySigningDriver(); + + // Stores signing identifier and a new nonce in provided message for signing operations. + // All space in message payload buffer is used for signing identifier and nonce. + // Returns false if subsystem is busy processing an ongoing signing operation. + // If successful, this marks the start of a signing operation at the receiving side so + // implementation is expected to do any necessary initializations within this call. + virtual bool getNonce(MyMessage &msg) = 0; + + // Check timeout of verification session. + // Nonce will be purged if it takes too long for a signed message to be sent to the receiver. + // This function should be called on regular intervals. + virtual bool checkTimer(void) = 0; + + // Get nonce from provided message and store for signing operations. + // Returns false if subsystem is busy processing an ongoing signing operation. + // Returns false if signing identifier found in message is not supported by the used backend. + // If successful, this marks the start of a signing operation at the sending side so + // implementation is expected to do any necessary initializations within this call. + virtual bool putNonce(MyMessage &msg) = 0; + + // Signs provided message. All remaining space in message payload buffer is used for signing + // identifier and signature. + // Nonce used for signature calculation is the one generated previously using getNonce(). + // Nonce will be cleared when this function is called to prevent re-use of nonce. + // Returns false if subsystem is busy processing an ongoing signing operation. + // Returns false if not two bytes or more of free payload space is left in provided message. + // This ends a signing operation at the sending side so implementation is expected to do any + // deinitializations and enter a power saving state within this call. + virtual bool signMsg(MyMessage &msg) = 0; + + // Verifies signature in provided message. + // Nonce used for verification is the one previously set using putNonce(). + // Nonce will be cleared when this function is called to prevent re-use of nonce. + // Returns false if subsystem is busy processing an ongoing signing operation. + // Returns false if signing identifier found in message is not supported by the used backend. + // This ends a signing operation at the receiving side so implementation is expected to do any + // deinitializations and enter a power saving state within this call. + virtual bool verifyMsg(MyMessage &msg) = 0; +}; + +#endif From fca0d4b5449c6ae6ab73f1e555be7deab99a650e Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 7 Feb 2015 09:52:37 +0100 Subject: [PATCH 042/137] Dummy signing driver backend The dummy signing driver implements the most rudimentary form of signing. No pre-shared key is used, nonce is simply incremeted each turn and signature is only calculated on the fist byte using data XOR nonce. This driver is intended for library debugging and sensor network integrity verification (signed messages will force the radio to transmit all 32 bytes of data). It does check SIGNING_IDENTIFIER byte to avoid illegal mixing of signing backends in the network (as seen by this node) and it does verify proper execution order on the API. The dummy driver rejects all other signing backend protocols. Signing backend is selected in MyConfig.h --- libraries/MySensors/MyConfig.h | 14 +- libraries/MySensors/MySigningDriverDummy.cpp | 143 +++++++++++++++++++ libraries/MySensors/MySigningDriverDummy.h | 36 +++++ 3 files changed, 191 insertions(+), 2 deletions(-) create mode 100644 libraries/MySensors/MySigningDriverDummy.cpp create mode 100644 libraries/MySensors/MySigningDriverDummy.h diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 96f2253..ce4f0aa 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -15,9 +15,13 @@ #define MYSENSORS_RF_NRF24 //#define MYSENSORS_RF_RF69 +// Choose signing backend by enabling one of the following +#define MYSENSORS_SIGNING_DUMMY - - +// Define a suitable timeout for a signature verification session +// Consider the turnaround from a nonce being generated to a signed message being received +// which might vary, especially in networks with many hops. 5s ought to be enough for anyone. +#define VERIFICATION_TIMEOUT_MS 5000 #ifdef MYSENSORS_RF_NRF24 #include "MyRFDriverNRF24.h" @@ -29,6 +33,12 @@ typedef class MyRFDriverNRF24 MyRFDriverClass; typedef class MyRFDriverRF69 MyRFDriverClass; #endif +#ifdef MYSENSORS_SIGNING_DUMMY +#include "MySigningDriverDummy.h" +#define SIGNING_IDENTIFIER (0) // Reserved for dummy implementation, will not work with other backends +typedef class MySigningDriverDummy MySigningDriverClass; +#endif + /*** * Enable/Disable debug logging */ diff --git a/libraries/MySensors/MySigningDriverDummy.cpp b/libraries/MySensors/MySigningDriverDummy.cpp new file mode 100644 index 0000000..51d418f --- /dev/null +++ b/libraries/MySensors/MySigningDriverDummy.cpp @@ -0,0 +1,143 @@ +/* + Dummy signing backend. Does not provide any security measures. + + Created by Patrick "Anticimex" Fallberg +*/ +#include "MySigningDriver.h" +#include "MySigningDriverDummy.h" + +#ifdef MYSENSORS_SIGNING_DUMMY +// Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) +//#define DEBUG_DUMMY_SIGNING + +#ifdef DEBUG_DUMMY_SIGNING +#define DEBUG_DUMMY_PRINTLN(args) Serial.println(args) +#else +#define DEBUG_DUMMY_PRINTLN(args) +#endif + +#ifdef DEBUG_DUMMY_SIGNING +static void DEBUG_DUMMY_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) +{ + int i; + Serial.println(str); + for (int i=0; i timestamp + VERIFICATION_TIMEOUT_MS) { + DEBUG_DUMMY_PRINTLN("Verification timeout"); + // Purge nonce + current_nonce = 0; // purge nonce when used + verification_ongoing = false; + return false; + } + } + return true; +} + +bool MySigningDriverDummy::putNonce(MyMessage &msg) { + if (mGetLength(msg) != 2) { + DEBUG_DUMMY_PRINTLN("Incoming nonce with incorrect size"); + return false; // We require a signing identifier and a 1byte nonce + } + + if (((uint8_t*)msg.getCustom())[0] != SIGNING_IDENTIFIER) { + DEBUG_DUMMY_PRINTLN("Incorrect signing identifier"); + return false; + } + + current_nonce = ((uint8_t*)msg.getCustom())[1]; + return true; +} + +bool MySigningDriverDummy::signMsg(MyMessage &msg) { + // If we cannot fit any signature in the message, refuse to sign it + if (mGetLength(msg) > MAX_PAYLOAD-2) { + DEBUG_DUMMY_PRINTLN("Cannot fit any signature to this message"); + return false; + } + + // Calculate signature of message + mSetSigned(msg, 1); // make sure signing flag is set before signature is calculated + DEBUG_DUMMY_PRINTBUF("Message to sign:", (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); + uint8_t signature = msg.data[0] ^ current_nonce; + msg.data[mGetLength(msg)] = SIGNING_IDENTIFIER; // Add signing identifier + msg.data[mGetLength(msg)+1] = signature; + current_nonce = 0; // purge nonce when used + return true; +} + +bool MySigningDriverDummy::verifyMsg(MyMessage &msg) { + if (!verification_ongoing) { + DEBUG_DUMMY_PRINTLN("No active verification session"); + return false; + } else { + // Make sure we have not expired + if (!checkTimer()) { + return false; + } + + verification_ongoing = false; + + if (msg.data[mGetLength(msg)] != SIGNING_IDENTIFIER) { + DEBUG_DUMMY_PRINTLN("Incorrect signing identifier"); + return false; + } + + DEBUG_DUMMY_PRINTBUF("Message to verify:", (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); + DEBUG_DUMMY_PRINTBUF("Signature in message:", (uint8_t*)&msg.data[mGetLength(msg)], 2); + + // The dummy signing is the nonce XOR the first payload byte, + // so we "verify" by redoing that calculation with the nonce we transmitted + // Message without a payload this implementation always accepts as signed and messages that cannot + // fit a signature are also accepted as signed + if (mGetLength(msg) && mGetLength(msg) < MAX_PAYLOAD-2) { + uint8_t signature = msg.data[0] ^ current_nonce; + if (msg.data[mGetLength(msg)+1] != signature) { + DEBUG_DUMMY_PRINTBUF("Signature bad. Calculated signature:", &signature, 1); + return false; + } else { + DEBUG_DUMMY_PRINTLN("Signature ok"); + return true; + } + } else { + DEBUG_DUMMY_PRINTLN("No signature in message"); + return false; + } + } +} +#endif diff --git a/libraries/MySensors/MySigningDriverDummy.h b/libraries/MySensors/MySigningDriverDummy.h new file mode 100644 index 0000000..74b88a6 --- /dev/null +++ b/libraries/MySensors/MySigningDriverDummy.h @@ -0,0 +1,36 @@ +/* + Dummy signing backend. Does not provide any security measures. + + Created by Patrick "Anticimex" Fallberg +*/ +#ifndef MySigningDriverDummy_h +#define MySigningDriverDummy_h + +#include "MyConfig.h" +#include "MySigningDriver.h" +#include + +// The dummy signing driver implements the most rudimentary form of signing +// No pre-shared key is used, nonce is simply incremeted each turn and signature +// is only calculated on the fist byte using data XOR nonce. +// This driver is intended for library debugging and sensor network integrity +// verification (signed messages will force the radio to transmit all 32 bytes of data). +// It does check SIGNING_IDENTIFIER byte to avoid illegal mixing of signing back-ends in +// the network (as seen by this node) and it does verify proper execution order on the API. +// The dummy driver rejects all other back-ends. +class MySigningDriverDummy : public MySigningDriver +{ +public: + MySigningDriverDummy(); + bool getNonce(MyMessage &msg); + bool checkTimer(void); + bool putNonce(MyMessage &msg); + bool signMsg(MyMessage &msg); + bool verifyMsg(MyMessage &msg); +private: + unsigned long timestamp; + bool verification_ongoing; + uint8_t current_nonce; +}; + +#endif From ce290e280ea03e77bcb1288e6861f5e1557a8085 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Mon, 9 Feb 2015 20:11:11 +0100 Subject: [PATCH 043/137] ATSHA204 signing backend Default SDA pin is A3 for single wire communication. The pin is selected in MyConfig.h. I2C variant of ATSHA204 is not supported. Messages are signed using HMAC-SHA256 where some parts of the message digest are ATSHA204 specific. --- libraries/MySensors/MyConfig.h | 19 + .../MySensors/MySigningDriverAtsha204.cpp | 217 ++++++++ libraries/MySensors/MySigningDriverAtsha204.h | 37 ++ libraries/MySensors/utility/ATSHA204.cpp | 521 ++++++++++++++++++ libraries/MySensors/utility/ATSHA204.h | 206 +++++++ 5 files changed, 1000 insertions(+) create mode 100644 libraries/MySensors/MySigningDriverAtsha204.cpp create mode 100644 libraries/MySensors/MySigningDriverAtsha204.h create mode 100644 libraries/MySensors/utility/ATSHA204.cpp create mode 100644 libraries/MySensors/utility/ATSHA204.h diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index ce4f0aa..82c02da 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -17,6 +17,7 @@ // Choose signing backend by enabling one of the following #define MYSENSORS_SIGNING_DUMMY +//#define MYSENSORS_SIGNING_ATSHA204 // Define a suitable timeout for a signature verification session // Consider the turnaround from a nonce being generated to a signed message being received @@ -39,6 +40,24 @@ typedef class MyRFDriverRF69 MyRFDriverClass; typedef class MySigningDriverDummy MySigningDriverClass; #endif +#ifdef MYSENSORS_SIGNING_ATSHA204 +#ifdef MYSENSORS_SENSOR +#define ATSHA204_PIN 17 //A3 +#endif + +#ifdef MYSENSORS_SERIAL_GATEWAY +#define ATSHA204_PIN 17 //A3 +#endif + +#ifdef MYSENSORS_ETHERNET_MQTT_GATEWAY +#define ATSHA204_PIN 17 //A3 +#endif + +#include "MySigningDriverAtsha204.h" +#define SIGNING_IDENTIFIER (1) // SHA256-based HMAC (ATSHA204 specific) +typedef class MySigningDriverAtsha204 MySigningDriverClass; +#endif + /*** * Enable/Disable debug logging */ diff --git a/libraries/MySensors/MySigningDriverAtsha204.cpp b/libraries/MySensors/MySigningDriverAtsha204.cpp new file mode 100644 index 0000000..a71a30a --- /dev/null +++ b/libraries/MySensors/MySigningDriverAtsha204.cpp @@ -0,0 +1,217 @@ +/* + ATSHA204 signing backend. The Atmel ATSHA204 offers true random number generation and + HMAC-SHA256 authentication with a readout-protected key. + + Created by Patrick "Anticimex" Fallberg +*/ +#include "MySigningDriver.h" +#include "MySigningDriverAtsha204.h" + +#ifdef MYSENSORS_SIGNING_ATSHA204 +// Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) +//#define DEBUG_ATSHA_SIGNING + +#ifdef DEBUG_ATSHA_SIGNING +#define DEBUG_ATSHA_PRINTLN(args) Serial.println(args) +#else +#define DEBUG_ATSHA_PRINTLN(args) +#endif + +#ifdef DEBUG_ATSHA_SIGNING +static void DEBUG_ATSHA_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) +{ + int i; + Serial.println(str); + for (int i=0; i timestamp + VERIFICATION_TIMEOUT_MS) { + DEBUG_ATSHA_PRINTLN("Verification timeout"); + // Purge nonce + memset(current_nonce, 0xAA, NONCE_NUMIN_SIZE_PASSTHROUGH); + verification_ongoing = false; + return false; + } + } + return true; +} + +bool MySigningDriverAtsha204::putNonce(MyMessage &msg) { + if (mGetLength(msg) != MAX_PAYLOAD) { + DEBUG_ATSHA_PRINTLN("Incoming nonce with incorrect size"); + return false; // We require as big nonce as possible + } + + if (((uint8_t*)msg.getCustom())[0] != SIGNING_IDENTIFIER) { + DEBUG_ATSHA_PRINTLN("Incorrect signing identifier"); + return false; + } + + memcpy(current_nonce, (uint8_t*)msg.getCustom(), MAX_PAYLOAD); + return true; +} + +bool MySigningDriverAtsha204::signMsg(MyMessage &msg) { + // If we cannot fit any signature in the message, refuse to sign it + if (mGetLength(msg) > MAX_PAYLOAD-2) { + DEBUG_ATSHA_PRINTLN("Cannot fit any signature to this message"); + return false; + } + + // Calculate signature of message + mSetSigned(msg, 1); // make sure signing flag is set before signature is calculated + DEBUG_ATSHA_PRINTBUF("Message to sign:", (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); + if (!calculateSignature(msg)) { + DEBUG_ATSHA_PRINTLN("Failed to calculate signature"); + mSetSigned(msg, 0); // make sure signing flag is truthful + return false; + } + + // Transfer as much signature data as the remaining space in the message permits + memcpy(&msg.data[mGetLength(msg)], &rx_buffer[SHA204_BUFFER_POS_DATA], MAX_PAYLOAD-mGetLength(msg)); + + return true; +} + +bool MySigningDriverAtsha204::verifyMsg(MyMessage &msg) { + if (!verification_ongoing) { + DEBUG_ATSHA_PRINTLN("No active verification session"); + return false; + } else { + // Make sure we have not expired + if (!checkTimer()) { + return false; + } + + verification_ongoing = false; + + if (msg.data[mGetLength(msg)] != SIGNING_IDENTIFIER) { + DEBUG_ATSHA_PRINTLN("Incorrect signing identifier"); + return false; + } + + DEBUG_ATSHA_PRINTBUF("Message to verify:", (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); + DEBUG_ATSHA_PRINTBUF("Signature in message:", (uint8_t*)&msg.data[mGetLength(msg)], MAX_PAYLOAD-mGetLength(msg)); + + // Get signature of message + if (!calculateSignature(msg)) { + DEBUG_ATSHA_PRINTLN("Failed to calculate signature"); + return false; + } + + // Compare the caluclated signature with the provided signature + if (memcmp(&msg.data[mGetLength(msg)], &rx_buffer[SHA204_BUFFER_POS_DATA], MAX_PAYLOAD-mGetLength(msg))) { + DEBUG_ATSHA_PRINTBUF("Signature bad. Calculated signature:", &rx_buffer[SHA204_BUFFER_POS_DATA], MAX_PAYLOAD-mGetLength(msg)); + return false; + } else { + DEBUG_ATSHA_PRINTLN("Signature ok"); + return true; + } + } +} + +// Helper to calculate signature of msg (returned in rx_buffer[SHA204_BUFFER_POS_DATA]) +bool MySigningDriverAtsha204::calculateSignature(MyMessage &msg) { + memset(temp_message, 0, 32); + memcpy(temp_message, (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); + + // Wake device before starting operations + if (atsha204.sha204c_wakeup(rx_buffer) != SHA204_SUCCESS) return false; + + // Program the data to sign into the ATSHA204 + if (atsha204.sha204m_execute(SHA204_WRITE, SHA204_ZONE_DATA | SHA204_ZONE_COUNT_FLAG, 8 << 3, 32, temp_message, + WRITE_COUNT_LONG, tx_buffer, WRITE_RSP_SIZE, rx_buffer) != SHA204_SUCCESS) { + DEBUG_ATSHA_PRINTLN("Failed to program data"); + return false; + } + + // Program the nonce to use for the signature (has to be done just before GENDIG due to chip limitations) + if (atsha204.sha204m_execute(SHA204_NONCE, NONCE_MODE_PASSTHROUGH, 0, NONCE_NUMIN_SIZE_PASSTHROUGH, current_nonce, + NONCE_COUNT_LONG, tx_buffer, NONCE_RSP_SIZE_SHORT, rx_buffer) != SHA204_SUCCESS) { + DEBUG_ATSHA_PRINTLN("Failed to program nonce"); + // Purge nonce when used + memset(current_nonce, 0xAA, NONCE_NUMIN_SIZE_PASSTHROUGH); + return false; + } + + // Purge nonce when used + memset(current_nonce, 0xAA, NONCE_NUMIN_SIZE_PASSTHROUGH); + + // Generate digest of data and nonce + if (atsha204.sha204m_execute(SHA204_GENDIG, GENDIG_ZONE_DATA, 8, 0, NULL, + GENDIG_COUNT_DATA, tx_buffer, GENDIG_RSP_SIZE, rx_buffer) != SHA204_SUCCESS) { + DEBUG_ATSHA_PRINTLN("Failed to generate digest"); + return false; + } + + // Calculate HMAC of message+nonce digest and secret key + if (atsha204.sha204m_execute(SHA204_HMAC, HMAC_MODE_SOURCE_FLAG_MATCH, 0, 0, NULL, + HMAC_COUNT, tx_buffer, HMAC_RSP_SIZE, rx_buffer) != SHA204_SUCCESS) { + DEBUG_ATSHA_PRINTLN("Failed to generate HMAC"); + return false; + } + + // Put device back to sleep + atsha204.sha204c_sleep(); + + // Overwrite the first byte in the signature with the signing identifier + rx_buffer[SHA204_BUFFER_POS_DATA] = SIGNING_IDENTIFIER; + + DEBUG_ATSHA_PRINTBUF("HMAC:", &rx_buffer[SHA204_BUFFER_POS_DATA], 32); + return true; // We return with the signature in rx_buffer[SHA204_BUFFER_POS_DATA] +} +#endif diff --git a/libraries/MySensors/MySigningDriverAtsha204.h b/libraries/MySensors/MySigningDriverAtsha204.h new file mode 100644 index 0000000..a2f6b9d --- /dev/null +++ b/libraries/MySensors/MySigningDriverAtsha204.h @@ -0,0 +1,37 @@ +/* + ATSHA204 signing backend. The Atmel ATSHA204 offers true random number generation and + HMAC-SHA256 authentication with a readout-protected key. + + Created by Patrick "Anticimex" Fallberg +*/ +#ifndef MySigningDriverAtsha204_h +#define MySigningDriverAtsha204_h + +#include "MyConfig.h" +#include "MySigningDriver.h" +#include "utility/ATSHA204.h" +#include + +// The ATSHA204 is capable of generating proper random numbers for nonce +// and can calculate HMAC-SHA256 signatures. This is enterprise- +// level of security and ought to implement the signing needs for anybody. +class MySigningDriverAtsha204 : public MySigningDriver +{ +public: + MySigningDriverAtsha204(); + bool getNonce(MyMessage &msg); + bool checkTimer(void); + bool putNonce(MyMessage &msg); + bool signMsg(MyMessage &msg); + bool verifyMsg(MyMessage &msg); +private: + unsigned long timestamp; + bool verification_ongoing; + uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH]; + uint8_t temp_message[32]; + uint8_t rx_buffer[SHA204_RSP_SIZE_MAX]; + uint8_t tx_buffer[SHA204_CMD_SIZE_MAX]; + bool calculateSignature(MyMessage &msg); +}; + +#endif diff --git a/libraries/MySensors/utility/ATSHA204.cpp b/libraries/MySensors/utility/ATSHA204.cpp new file mode 100644 index 0000000..da63668 --- /dev/null +++ b/libraries/MySensors/utility/ATSHA204.cpp @@ -0,0 +1,521 @@ +#include "Arduino.h" +#include "ATSHA204.h" + +// atsha204Class Constructor +// Feed this function the Arduino-ized pin number you want to assign to the ATSHA204's SDA pin +// This will find the DDRX, PORTX, and PINX registrs it'll need to point to to control that pin +// As well as the bit value for each of those registers +atsha204Class::atsha204Class(uint8_t pin) +{ + device_pin = digitalPinToBitMask(pin); // Find the bit value of the pin + uint8_t port = digitalPinToPort(pin); // temoporarily used to get the next three registers + + // Point to data direction register port of pin + device_port_DDR = portModeRegister(port); + // Point to output register of pin + device_port_OUT = portOutputRegister(port); + // Point to input register of pin + device_port_IN = portInputRegister(port); +} + +/* SWI bit bang functions */ + +void atsha204Class::swi_set_signal_pin(uint8_t is_high) +{ + *device_port_DDR |= device_pin; + + if (is_high) + *device_port_OUT |= device_pin; + else + *device_port_OUT &= ~device_pin; +} + +uint8_t atsha204Class::swi_send_bytes(uint8_t count, uint8_t *buffer) +{ + uint8_t i, bit_mask; + + // Disable interrupts while sending. + noInterrupts(); //swi_disable_interrupts(); + + // Set signal pin as output. + *device_port_OUT |= device_pin; + *device_port_DDR |= device_pin; + + // Wait turn around time. + delayMicroseconds(RX_TX_DELAY); //RX_TX_DELAY; + + for (i = 0; i < count; i++) + { + for (bit_mask = 1; bit_mask > 0; bit_mask <<= 1) + { + if (bit_mask & buffer[i]) + { + *device_port_OUT &= ~device_pin; + delayMicroseconds(BIT_DELAY); //BIT_DELAY_1; + *device_port_OUT |= device_pin; + delayMicroseconds(7*BIT_DELAY); //BIT_DELAY_7; + } + else + { + // Send a zero bit. + *device_port_OUT &= ~device_pin; + delayMicroseconds(BIT_DELAY); //BIT_DELAY_1; + *device_port_OUT |= device_pin; + delayMicroseconds(BIT_DELAY); //BIT_DELAY_1; + *device_port_OUT &= ~device_pin; + delayMicroseconds(BIT_DELAY); //BIT_DELAY_1; + *device_port_OUT |= device_pin; + delayMicroseconds(5*BIT_DELAY); //BIT_DELAY_5; + } + } + } + interrupts(); //swi_enable_interrupts(); + return SWI_FUNCTION_RETCODE_SUCCESS; +} + +uint8_t atsha204Class::swi_send_byte(uint8_t value) +{ + return swi_send_bytes(1, &value); +} + +uint8_t atsha204Class::swi_receive_bytes(uint8_t count, uint8_t *buffer) +{ + uint8_t status = SWI_FUNCTION_RETCODE_SUCCESS; + uint8_t i; + uint8_t bit_mask; + uint8_t pulse_count; + uint8_t timeout_count; + + // Disable interrupts while receiving. + noInterrupts(); //swi_disable_interrupts(); + + // Configure signal pin as input. + *device_port_DDR &= ~device_pin; + + // Receive bits and store in buffer. + for (i = 0; i < count; i++) + { + for (bit_mask = 1; bit_mask > 0; bit_mask <<= 1) + { + pulse_count = 0; + + // Make sure that the variable below is big enough. + // Change it to uint16_t if 255 is too small, but be aware that + // the loop resolution decreases on an 8-bit controller in that case. + timeout_count = START_PULSE_TIME_OUT; + + // Detect start bit. + while (--timeout_count > 0) + { + // Wait for falling edge. + if ((*device_port_IN & device_pin) == 0) + break; + } + + if (timeout_count == 0) + { + status = SWI_FUNCTION_RETCODE_TIMEOUT; + break; + } + + do + { + // Wait for rising edge. + if ((*device_port_IN & device_pin) != 0) + { + // For an Atmel microcontroller this might be faster than "pulse_count++". + pulse_count = 1; + break; + } + } while (--timeout_count > 0); + + if (pulse_count == 0) + { + status = SWI_FUNCTION_RETCODE_TIMEOUT; + break; + } + + // Trying to measure the time of start bit and calculating the timeout + // for zero bit detection is not accurate enough for an 8 MHz 8-bit CPU. + // So let's just wait the maximum time for the falling edge of a zero bit + // to arrive after we have detected the rising edge of the start bit. + timeout_count = ZERO_PULSE_TIME_OUT; + + // Detect possible edge indicating zero bit. + do + { + if ((*device_port_IN & device_pin) == 0) + { + // For an Atmel microcontroller this might be faster than "pulse_count++". + pulse_count = 2; + break; + } + } while (--timeout_count > 0); + + // Wait for rising edge of zero pulse before returning. Otherwise we might interpret + // its rising edge as the next start pulse. + if (pulse_count == 2) + { + do + { + if ((*device_port_IN & device_pin) != 0) + break; + } while (timeout_count-- > 0); + } + + // Update byte at current buffer index. + else + buffer[i] |= bit_mask; // received "one" bit + } + + if (status != SWI_FUNCTION_RETCODE_SUCCESS) + break; + } + interrupts(); //swi_enable_interrupts(); + + if (status == SWI_FUNCTION_RETCODE_TIMEOUT) + { + if (i > 0) + // Indicate that we timed out after having received at least one byte. + status = SWI_FUNCTION_RETCODE_RX_FAIL; + } + return status; +} + +/* Physical functions */ + +uint8_t atsha204Class::sha204c_sleep() +{ + return swi_send_byte(SHA204_SWI_FLAG_SLEEP); +} + +uint8_t atsha204Class::sha204p_receive_response(uint8_t size, uint8_t *response) +{ + uint8_t count_byte; + uint8_t i; + uint8_t ret_code; + + for (i = 0; i < size; i++) + response[i] = 0; + + (void) swi_send_byte(SHA204_SWI_FLAG_TX); + + ret_code = swi_receive_bytes(size, response); + if (ret_code == SWI_FUNCTION_RETCODE_SUCCESS || ret_code == SWI_FUNCTION_RETCODE_RX_FAIL) + { + count_byte = response[SHA204_BUFFER_POS_COUNT]; + if ((count_byte < SHA204_RSP_SIZE_MIN) || (count_byte > size)) + return SHA204_INVALID_SIZE; + + return SHA204_SUCCESS; + } + + // Translate error so that the Communication layer + // can distinguish between a real error or the + // device being busy executing a command. + if (ret_code == SWI_FUNCTION_RETCODE_TIMEOUT) + return SHA204_RX_NO_RESPONSE; + else + return SHA204_RX_FAIL; +} + +/* Communication functions */ + +uint8_t atsha204Class::sha204c_wakeup(uint8_t *response) +{ + swi_set_signal_pin(0); + delayMicroseconds(10*SHA204_WAKEUP_PULSE_WIDTH); + swi_set_signal_pin(1); + delay(SHA204_WAKEUP_DELAY); + + uint8_t ret_code = sha204p_receive_response(SHA204_RSP_SIZE_MIN, response); + if (ret_code != SHA204_SUCCESS) + return ret_code; + + // Verify status response. + if (response[SHA204_BUFFER_POS_COUNT] != SHA204_RSP_SIZE_MIN) + ret_code = SHA204_INVALID_SIZE; + else if (response[SHA204_BUFFER_POS_STATUS] != SHA204_STATUS_BYTE_WAKEUP) + ret_code = SHA204_COMM_FAIL; + else + { + if ((response[SHA204_RSP_SIZE_MIN - SHA204_CRC_SIZE] != 0x33) + || (response[SHA204_RSP_SIZE_MIN + 1 - SHA204_CRC_SIZE] != 0x43)) + ret_code = SHA204_BAD_CRC; + } + if (ret_code != SHA204_SUCCESS) + delay(SHA204_COMMAND_EXEC_MAX); + + return ret_code; +} + +uint8_t atsha204Class::sha204c_resync(uint8_t size, uint8_t *response) +{ + // Try to re-synchronize without sending a Wake token + // (step 1 of the re-synchronization process). + delay(SHA204_SYNC_TIMEOUT); + uint8_t ret_code = sha204p_receive_response(size, response); + if (ret_code == SHA204_SUCCESS) + return ret_code; + + // We lost communication. Send a Wake pulse and try + // to receive a response (steps 2 and 3 of the + // re-synchronization process). + (void) sha204c_sleep(); + ret_code = sha204c_wakeup(response); + + // Translate a return value of success into one + // that indicates that the device had to be woken up + // and might have lost its TempKey. + return (ret_code == SHA204_SUCCESS ? SHA204_RESYNC_WITH_WAKEUP : ret_code); +} + +uint8_t atsha204Class::sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer, uint8_t execution_delay, uint8_t execution_timeout) +{ + uint8_t ret_code = SHA204_FUNC_FAIL; + uint8_t ret_code_resync; + uint8_t n_retries_send; + uint8_t n_retries_receive; + uint8_t i; + uint8_t status_byte; + uint8_t count = tx_buffer[SHA204_BUFFER_POS_COUNT]; + uint8_t count_minus_crc = count - SHA204_CRC_SIZE; + uint16_t execution_timeout_us = (uint16_t) (execution_timeout * 1000) + SHA204_RESPONSE_TIMEOUT; + volatile uint16_t timeout_countdown; + + // Append CRC. + sha204c_calculate_crc(count_minus_crc, tx_buffer, tx_buffer + count_minus_crc); + + // Retry loop for sending a command and receiving a response. + n_retries_send = SHA204_RETRY_COUNT + 1; + + while ((n_retries_send-- > 0) && (ret_code != SHA204_SUCCESS)) + { + // Send command. + ret_code = swi_send_byte(SHA204_SWI_FLAG_CMD); + if (ret_code != SWI_FUNCTION_RETCODE_SUCCESS) + ret_code = SHA204_COMM_FAIL; + else + ret_code = swi_send_bytes(count, tx_buffer); + + if (ret_code != SHA204_SUCCESS) + { + if (sha204c_resync(rx_size, rx_buffer) == SHA204_RX_NO_RESPONSE) + return ret_code; // The device seems to be dead in the water. + else + continue; + } + + // Wait minimum command execution time and then start polling for a response. + delay(execution_delay); + + // Retry loop for receiving a response. + n_retries_receive = SHA204_RETRY_COUNT + 1; + while (n_retries_receive-- > 0) + { + // Reset response buffer. + for (i = 0; i < rx_size; i++) + rx_buffer[i] = 0; + + // Poll for response. + timeout_countdown = execution_timeout_us; + do + { + ret_code = sha204p_receive_response(rx_size, rx_buffer); + timeout_countdown -= SHA204_RESPONSE_TIMEOUT; + } + while ((timeout_countdown > SHA204_RESPONSE_TIMEOUT) && (ret_code == SHA204_RX_NO_RESPONSE)); + + if (ret_code == SHA204_RX_NO_RESPONSE) + { + // We did not receive a response. Re-synchronize and send command again. + if (sha204c_resync(rx_size, rx_buffer) == SHA204_RX_NO_RESPONSE) + // The device seems to be dead in the water. + return ret_code; + else + break; + } + + // Check whether we received a valid response. + if (ret_code == SHA204_INVALID_SIZE) + { + // We see 0xFF for the count when communication got out of sync. + ret_code_resync = sha204c_resync(rx_size, rx_buffer); + if (ret_code_resync == SHA204_SUCCESS) + // We did not have to wake up the device. Try receiving response again. + continue; + if (ret_code_resync == SHA204_RESYNC_WITH_WAKEUP) + // We could re-synchronize, but only after waking up the device. + // Re-send command. + break; + else + // We failed to re-synchronize. + return ret_code; + } + + // We received a response of valid size. + // Check the consistency of the response. + ret_code = sha204c_check_crc(rx_buffer); + if (ret_code == SHA204_SUCCESS) + { + // Received valid response. + if (rx_buffer[SHA204_BUFFER_POS_COUNT] > SHA204_RSP_SIZE_MIN) + // Received non-status response. We are done. + return ret_code; + + // Received status response. + status_byte = rx_buffer[SHA204_BUFFER_POS_STATUS]; + + // Translate the three possible device status error codes + // into library return codes. + if (status_byte == SHA204_STATUS_BYTE_PARSE) + return SHA204_PARSE_ERROR; + if (status_byte == SHA204_STATUS_BYTE_EXEC) + return SHA204_CMD_FAIL; + if (status_byte == SHA204_STATUS_BYTE_COMM) + { + // In case of the device status byte indicating a communication + // error this function exits the retry loop for receiving a response + // and enters the overall retry loop + // (send command / receive response). + ret_code = SHA204_STATUS_CRC; + break; + } + + // Received status response from CheckMAC, DeriveKey, GenDig, + // Lock, Nonce, Pause, UpdateExtra, or Write command. + return ret_code; + } + + else + { + // Received response with incorrect CRC. + ret_code_resync = sha204c_resync(rx_size, rx_buffer); + if (ret_code_resync == SHA204_SUCCESS) + // We did not have to wake up the device. Try receiving response again. + continue; + if (ret_code_resync == SHA204_RESYNC_WITH_WAKEUP) + // We could re-synchronize, but only after waking up the device. + // Re-send command. + break; + else + // We failed to re-synchronize. + return ret_code; + } // block end of check response consistency + + } // block end of receive retry loop + + } // block end of send and receive retry loop + + return ret_code; +} + + +/* Marshaling functions */ +uint8_t atsha204Class::sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t param2, + uint8_t datalen1, uint8_t *data1, uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer) +{ + uint8_t poll_delay, poll_timeout, response_size; + uint8_t *p_buffer; + uint8_t len; + + // Supply delays and response size. + switch (op_code) + { + case SHA204_GENDIG: + poll_delay = GENDIG_DELAY; + poll_timeout = GENDIG_EXEC_MAX - GENDIG_DELAY; + response_size = GENDIG_RSP_SIZE; + break; + + case SHA204_HMAC: + poll_delay = HMAC_DELAY; + poll_timeout = HMAC_EXEC_MAX - HMAC_DELAY; + response_size = HMAC_RSP_SIZE; + break; + + case SHA204_NONCE: + poll_delay = NONCE_DELAY; + poll_timeout = NONCE_EXEC_MAX - NONCE_DELAY; + response_size = param1 == NONCE_MODE_PASSTHROUGH + ? NONCE_RSP_SIZE_SHORT : NONCE_RSP_SIZE_LONG; + break; + + case SHA204_RANDOM: + poll_delay = RANDOM_DELAY; + poll_timeout = RANDOM_EXEC_MAX - RANDOM_DELAY; + response_size = RANDOM_RSP_SIZE; + break; + + case SHA204_WRITE: + poll_delay = WRITE_DELAY; + poll_timeout = WRITE_EXEC_MAX - WRITE_DELAY; + response_size = WRITE_RSP_SIZE; + break; + + default: + poll_delay = 0; + poll_timeout = SHA204_COMMAND_EXEC_MAX; + response_size = rx_size; + } + + // Assemble command. + len = datalen1 + SHA204_CMD_SIZE_MIN; + p_buffer = tx_buffer; + *p_buffer++ = len; + *p_buffer++ = op_code; + *p_buffer++ = param1; + *p_buffer++ = param2 & 0xFF; + *p_buffer++ = param2 >> 8; + + if (datalen1 > 0) { + memcpy(p_buffer, data1, datalen1); + p_buffer += datalen1; + } + + sha204c_calculate_crc(len - SHA204_CRC_SIZE, tx_buffer, p_buffer); + + // Send command and receive response. + return sha204c_send_and_receive(&tx_buffer[0], response_size, + &rx_buffer[0], poll_delay, poll_timeout); +} + +/* CRC Calculator and Checker */ + +void atsha204Class::sha204c_calculate_crc(uint8_t length, uint8_t *data, uint8_t *crc) +{ + uint8_t counter; + uint16_t crc_register = 0; + uint16_t polynom = 0x8005; + uint8_t shift_register; + uint8_t data_bit, crc_bit; + + for (counter = 0; counter < length; counter++) + { + for (shift_register = 0x01; shift_register > 0x00; shift_register <<= 1) + { + data_bit = (data[counter] & shift_register) ? 1 : 0; + crc_bit = crc_register >> 15; + + // Shift CRC to the left by 1. + crc_register <<= 1; + + if ((data_bit ^ crc_bit) != 0) + crc_register ^= polynom; + } + } + crc[0] = (uint8_t) (crc_register & 0x00FF); + crc[1] = (uint8_t) (crc_register >> 8); +} + +uint8_t atsha204Class::sha204c_check_crc(uint8_t *response) +{ + uint8_t crc[SHA204_CRC_SIZE]; + uint8_t count = response[SHA204_BUFFER_POS_COUNT]; + + count -= SHA204_CRC_SIZE; + sha204c_calculate_crc(count, response, crc); + + return (crc[0] == response[count] && crc[1] == response[count + 1]) + ? SHA204_SUCCESS : SHA204_BAD_CRC; +} \ No newline at end of file diff --git a/libraries/MySensors/utility/ATSHA204.h b/libraries/MySensors/utility/ATSHA204.h new file mode 100644 index 0000000..cb2abc8 --- /dev/null +++ b/libraries/MySensors/utility/ATSHA204.h @@ -0,0 +1,206 @@ +#ifndef ATSHA204_H +#define ATSHA204_H +#include "Arduino.h" + +/* This is a scaled down variant of the ATSHA204 library, tweaked to meet the specific needs of MySensors. */ + +/* Library return codes */ +#define SHA204_SUCCESS ((uint8_t) 0x00) //!< Function succeeded. +#define SHA204_PARSE_ERROR ((uint8_t) 0xD2) //!< response status byte indicates parsing error +#define SHA204_CMD_FAIL ((uint8_t) 0xD3) //!< response status byte indicates command execution error +#define SHA204_STATUS_CRC ((uint8_t) 0xD4) //!< response status byte indicates CRC error +#define SHA204_STATUS_UNKNOWN ((uint8_t) 0xD5) //!< response status byte is unknown +#define SHA204_FUNC_FAIL ((uint8_t) 0xE0) //!< Function could not execute due to incorrect condition / state. +#define SHA204_GEN_FAIL ((uint8_t) 0xE1) //!< unspecified error +#define SHA204_BAD_PARAM ((uint8_t) 0xE2) //!< bad argument (out of range, null pointer, etc.) +#define SHA204_INVALID_ID ((uint8_t) 0xE3) //!< invalid device id, id not set +#define SHA204_INVALID_SIZE ((uint8_t) 0xE4) //!< Count value is out of range or greater than buffer size. +#define SHA204_BAD_CRC ((uint8_t) 0xE5) //!< incorrect CRC received +#define SHA204_RX_FAIL ((uint8_t) 0xE6) //!< Timed out while waiting for response. Number of bytes received is > 0. +#define SHA204_RX_NO_RESPONSE ((uint8_t) 0xE7) //!< Not an error while the Command layer is polling for a command response. +#define SHA204_RESYNC_WITH_WAKEUP ((uint8_t) 0xE8) //!< re-synchronization succeeded, but only after generating a Wake-up + +#define SHA204_COMM_FAIL ((uint8_t) 0xF0) //!< Communication with device failed. Same as in hardware dependent modules. +#define SHA204_TIMEOUT ((uint8_t) 0xF1) //!< Timed out while waiting for response. Number of bytes received is 0. + +/* bitbang_config.h */ + +#define PORT_ACCESS_TIME (630) //! time it takes to toggle the pin at CPU clock of 16 MHz (ns) +#define START_PULSE_WIDTH (4340) //! width of start pulse (ns) +#define BIT_DELAY (4) //! delay macro for width of one pulse (start pulse or zero pulse, in ns) +#define RX_TX_DELAY (15) //! turn around time when switching from receive to transmit +#define START_PULSE_TIME_OUT (255) //! This value is decremented while waiting for the falling edge of a start pulse. +#define ZERO_PULSE_TIME_OUT (26) //! This value is decremented while waiting for the falling edge of a zero pulse. + +/* swi_phys.h */ + +#define SWI_FUNCTION_RETCODE_SUCCESS ((uint8_t) 0x00) //!< Communication with device succeeded. +#define SWI_FUNCTION_RETCODE_TIMEOUT ((uint8_t) 0xF1) //!< Communication timed out. +#define SWI_FUNCTION_RETCODE_RX_FAIL ((uint8_t) 0xF9) //!< Communication failed after at least one byte was received. + +/* sha204_physical.h */ + +#define SHA204_RSP_SIZE_MIN ((uint8_t) 4) //!< minimum number of bytes in response +#define SHA204_RSP_SIZE_MAX ((uint8_t) 35) //!< maximum size of response packet +#define SHA204_BUFFER_POS_COUNT (0) //!< buffer index of count byte in command or response +#define SHA204_BUFFER_POS_DATA (1) //!< buffer index of data in response +#define SHA204_WAKEUP_PULSE_WIDTH (uint8_t) (6.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5) //! width of Wakeup pulse in 10 us units +#define SHA204_WAKEUP_DELAY (uint8_t) (3.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5) //! delay between Wakeup pulse and communication in ms + +/* sha204_swi.c */ +#define SHA204_SWI_FLAG_CMD ((uint8_t) 0x77) //!< flag preceding a command +#define SHA204_SWI_FLAG_TX ((uint8_t) 0x88) //!< flag requesting a response +#define SHA204_SWI_FLAG_IDLE ((uint8_t) 0xBB) //!< flag requesting to go into Idle mode +#define SHA204_SWI_FLAG_SLEEP ((uint8_t) 0xCC) //!< flag requesting to go into Sleep mode + +/* sha204_comm_marshaling.h */ +// command op-code definitions +#define SHA204_GENDIG ((uint8_t) 0x15) //!< GenDig command op-code +#define SHA204_HMAC ((uint8_t) 0x11) //!< HMAC command op-code +#define SHA204_NONCE ((uint8_t) 0x16) //!< Nonce command op-code +#define SHA204_RANDOM ((uint8_t) 0x1B) //!< Random command op-code +#define SHA204_WRITE ((uint8_t) 0x12) //!< Write command op-code + +// packet size definitions +#define SHA204_RSP_SIZE_VAL ((uint8_t) 7) //!< size of response packet containing four bytes of data + +// definitions for command packet indexes common to all commands +#define SHA204_COUNT_IDX ( 0) //!< command packet index for count +#define SHA204_OPCODE_IDX ( 1) //!< command packet index for op-code +#define SHA204_PARAM1_IDX ( 2) //!< command packet index for first parameter +#define SHA204_PARAM2_IDX ( 3) //!< command packet index for second parameter +#define SHA204_DATA_IDX ( 5) //!< command packet index for second parameter + +// zone definitions +#define SHA204_ZONE_CONFIG ((uint8_t) 0x00) //!< Configuration zone +#define SHA204_ZONE_OTP ((uint8_t) 0x01) //!< OTP (One Time Programming) zone +#define SHA204_ZONE_DATA ((uint8_t) 0x02) //!< Data zone +#define SHA204_ZONE_MASK ((uint8_t) 0x03) //!< Zone mask +#define SHA204_ZONE_COUNT_FLAG ((uint8_t) 0x80) //!< Zone bit 7 set: Access 32 bytes, otherwise 4 bytes. +#define SHA204_ZONE_ACCESS_4 ((uint8_t) 4) //!< Read or write 4 bytes. +#define SHA204_ZONE_ACCESS_32 ((uint8_t) 32) //!< Read or write 32 bytes. +#define SHA204_ADDRESS_MASK_CONFIG ( 0x001F) //!< Address bits 5 to 7 are 0 for Configuration zone. +#define SHA204_ADDRESS_MASK_OTP ( 0x000F) //!< Address bits 4 to 7 are 0 for OTP zone. +#define SHA204_ADDRESS_MASK ( 0x007F) //!< Address bit 7 to 15 are always 0. + +// GenDig command definitions +#define GENDIG_ZONE_IDX SHA204_PARAM1_IDX //!< GenDig command index for zone +#define GENDIG_KEYID_IDX SHA204_PARAM2_IDX //!< GenDig command index for key id +#define GENDIG_DATA_IDX SHA204_DATA_IDX //!< GenDig command index for optional data +#define GENDIG_COUNT SHA204_CMD_SIZE_MIN //!< GenDig command packet size without "other data" +#define GENDIG_COUNT_DATA (11) //!< GenDig command packet size with "other data" +#define GENDIG_OTHER_DATA_SIZE (4) //!< GenDig size of "other data" +#define GENDIG_ZONE_CONFIG ((uint8_t) 0) //!< GenDig zone id config +#define GENDIG_ZONE_OTP ((uint8_t) 1) //!< GenDig zone id OTP +#define GENDIG_ZONE_DATA ((uint8_t) 2) //!< GenDig zone id data + +// HMAC command definitions +#define HMAC_MODE_IDX SHA204_PARAM1_IDX //!< HMAC command index for mode +#define HMAC_KEYID_IDX SHA204_PARAM2_IDX //!< HMAC command index for key id +#define HMAC_COUNT SHA204_CMD_SIZE_MIN //!< HMAC command packet size +#define HMAC_MODE_MASK ((uint8_t) 0x74) //!< HMAC mode bits 0, 1, 3, and 7 are 0. +#define HMAC_MODE_SOURCE_FLAG_MATCH ((uint8_t) 0x04) //!< HMAC mode bit 2: match TempKey.SourceFlag + +// Nonce command definitions +#define NONCE_MODE_IDX SHA204_PARAM1_IDX //!< Nonce command index for mode +#define NONCE_PARAM2_IDX SHA204_PARAM2_IDX //!< Nonce command index for 2. parameter +#define NONCE_INPUT_IDX SHA204_DATA_IDX //!< Nonce command index for input data +#define NONCE_COUNT_SHORT (27) //!< Nonce command packet size for 20 bytes of data +#define NONCE_COUNT_LONG (39) //!< Nonce command packet size for 32 bytes of data +#define NONCE_MODE_MASK ((uint8_t) 3) //!< Nonce mode bits 2 to 7 are 0. +#define NONCE_MODE_SEED_UPDATE ((uint8_t) 0x00) //!< Nonce mode: update seed +#define NONCE_MODE_NO_SEED_UPDATE ((uint8_t) 0x01) //!< Nonce mode: do not update seed +#define NONCE_MODE_INVALID ((uint8_t) 0x02) //!< Nonce mode 2 is invalid. +#define NONCE_MODE_PASSTHROUGH ((uint8_t) 0x03) //!< Nonce mode: pass-through +#define NONCE_NUMIN_SIZE (20) //!< Nonce data length +#define NONCE_NUMIN_SIZE_PASSTHROUGH (32) //!< Nonce data length in pass-through mode (mode = 3) + +// Random command definitions +#define RANDOM_MODE_IDX SHA204_PARAM1_IDX //!< Random command index for mode +#define RANDOM_PARAM2_IDX SHA204_PARAM2_IDX //!< Random command index for 2. parameter +#define RANDOM_COUNT SHA204_CMD_SIZE_MIN //!< Random command packet size +#define RANDOM_SEED_UPDATE ((uint8_t) 0x00) //!< Random mode for automatic seed update +#define RANDOM_NO_SEED_UPDATE ((uint8_t) 0x01) //!< Random mode for no seed update + +// Write command definitions +#define WRITE_ZONE_IDX SHA204_PARAM1_IDX //!< Write command index for zone +#define WRITE_ADDR_IDX SHA204_PARAM2_IDX //!< Write command index for address +#define WRITE_VALUE_IDX SHA204_DATA_IDX //!< Write command index for data +#define WRITE_MAC_VS_IDX ( 9) //!< Write command index for MAC following short data +#define WRITE_MAC_VL_IDX (37) //!< Write command index for MAC following long data +#define WRITE_COUNT_SHORT (11) //!< Write command packet size with short data and no MAC +#define WRITE_COUNT_LONG (39) //!< Write command packet size with long data and no MAC +#define WRITE_COUNT_SHORT_MAC (43) //!< Write command packet size with short data and MAC +#define WRITE_COUNT_LONG_MAC (71) //!< Write command packet size with long data and MAC +#define WRITE_MAC_SIZE (32) //!< Write MAC size +#define WRITE_ZONE_MASK ((uint8_t) 0xC3) //!< Write zone bits 2 to 5 are 0. +#define WRITE_ZONE_WITH_MAC ((uint8_t) 0x40) //!< Write zone bit 6: write encrypted with MAC + +// Response size definitions +#define GENDIG_RSP_SIZE SHA204_RSP_SIZE_MIN //!< response size of GenDig command +#define HMAC_RSP_SIZE SHA204_RSP_SIZE_MAX //!< response size of HMAC command +#define NONCE_RSP_SIZE_SHORT SHA204_RSP_SIZE_MIN //!< response size of Nonce command with mode[0:1] = 3 +#define NONCE_RSP_SIZE_LONG SHA204_RSP_SIZE_MAX //!< response size of Nonce command +#define RANDOM_RSP_SIZE SHA204_RSP_SIZE_MAX //!< response size of Random command +#define WRITE_RSP_SIZE SHA204_RSP_SIZE_MIN //!< response size of Write command + +// command timing definitions for minimum execution times (ms) +#define GENDIG_DELAY ((uint8_t) (11.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define HMAC_DELAY ((uint8_t) (27.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define NONCE_DELAY ((uint8_t) (22.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define RANDOM_DELAY ((uint8_t) (11.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define WRITE_DELAY ((uint8_t) ( 4.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) + +// command timing definitions for maximum execution times (ms) +#define GENDIG_EXEC_MAX ((uint8_t) (43.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define HMAC_EXEC_MAX ((uint8_t) (69.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define NONCE_EXEC_MAX ((uint8_t) (60.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define RANDOM_EXEC_MAX ((uint8_t) (50.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define WRITE_EXEC_MAX ((uint8_t) (42.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) + +/* from sha204_config.h */ + +#define CPU_CLOCK_DEVIATION_POSITIVE (1.01) +#define CPU_CLOCK_DEVIATION_NEGATIVE (0.99) +#define SHA204_RETRY_COUNT (1) +#define SWI_RECEIVE_TIME_OUT ((uint16_t) 163) //! #START_PULSE_TIME_OUT in us instead of loop counts +#define SWI_US_PER_BYTE ((uint16_t) 313) //! It takes 312.5 us to send a byte (9 single-wire bits / 230400 Baud * 8 flag bits). +#define SHA204_SYNC_TIMEOUT ((uint8_t) 85)//! delay before sending a transmit flag in the synchronization routine +#define SHA204_RESPONSE_TIMEOUT ((uint16_t) SWI_RECEIVE_TIME_OUT + SWI_US_PER_BYTE) //! SWI response timeout is the sum of receive timeout and the time it takes to send the TX flag. + +/* from sha204_comm.h */ + +#define SHA204_COMMAND_EXEC_MAX ((uint8_t) (69.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) //! maximum command delay +#define SHA204_CMD_SIZE_MIN ((uint8_t) 7) //! minimum number of bytes in command (from count byte to second CRC byte) +#define SHA204_CMD_SIZE_MAX ((uint8_t) NONCE_COUNT_LONG) //! maximum size of command packet (Nonce) +#define SHA204_CRC_SIZE ((uint8_t) 2) //! number of CRC bytes +#define SHA204_BUFFER_POS_STATUS (1) //! buffer index of status byte in status response +#define SHA204_BUFFER_POS_DATA (1) //! buffer index of first data byte in data response +#define SHA204_STATUS_BYTE_WAKEUP ((uint8_t) 0x11) //! command parse error +#define SHA204_STATUS_BYTE_PARSE ((uint8_t) 0x03) //! command parse error +#define SHA204_STATUS_BYTE_EXEC ((uint8_t) 0x0F) //! command execution error +#define SHA204_STATUS_BYTE_COMM ((uint8_t) 0xFF) //! communication error + +class atsha204Class +{ +private: + uint8_t device_pin; + volatile uint8_t *device_port_DDR, *device_port_OUT, *device_port_IN; + void sha204c_calculate_crc(uint8_t length, uint8_t *data, uint8_t *crc); + uint8_t sha204c_check_crc(uint8_t *response); + void swi_set_signal_pin(uint8_t is_high); + uint8_t swi_receive_bytes(uint8_t count, uint8_t *buffer); + uint8_t swi_send_bytes(uint8_t count, uint8_t *buffer); + uint8_t swi_send_byte(uint8_t value); + uint8_t sha204p_receive_response(uint8_t size, uint8_t *response); +public: + atsha204Class(uint8_t pin); // Constructor + uint8_t sha204c_wakeup(uint8_t *response); + uint8_t sha204c_sleep(); + uint8_t sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer, uint8_t execution_delay, uint8_t execution_timeout); + uint8_t sha204c_resync(uint8_t size, uint8_t *response); + uint8_t sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t param2, + uint8_t datalen1, uint8_t *data1, uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer); +}; + +#endif From 911ae9c9d924ca879610112fa71d1b9823b17ae2 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Tue, 17 Feb 2015 23:10:56 +0100 Subject: [PATCH 044/137] ATSHA204 emulated signing backend ATSHA204 emulated signing backend. The emulated ATSHA204 implementation offers pseudo random number generation and HMAC-SHA256 authentication compatible with a "physical" ATSHA204. NOTE: Key is stored in clear text in the Arduino firmware. Therefore, the use of this back-end could compromise the key used in the signed message infrastructure if device is lost and its memory dumped. The seed for the random number generated is sampled from an analog pin. The pin is set in MyConfig.h using RANDOMSEED_PIN. The pin should be unconnected. The key to use for HMAC calculations must match the key used by other nodes this node will exchange signed messages with. The key for ATSHA204 emulator is set in MyConfig.h using hmacKey. --- libraries/MySensors/MyConfig.h | 28 +++ .../MySensors/MySigningDriverAtsha204Soft.cpp | 225 ++++++++++++++++++ .../MySensors/MySigningDriverAtsha204Soft.h | 43 ++++ libraries/MySensors/utility/sha256.cpp | 167 +++++++++++++ libraries/MySensors/utility/sha256.h | 40 ++++ 5 files changed, 503 insertions(+) create mode 100644 libraries/MySensors/MySigningDriverAtsha204Soft.cpp create mode 100644 libraries/MySensors/MySigningDriverAtsha204Soft.h create mode 100644 libraries/MySensors/utility/sha256.cpp create mode 100644 libraries/MySensors/utility/sha256.h diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 82c02da..0ffab4e 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -18,6 +18,7 @@ // Choose signing backend by enabling one of the following #define MYSENSORS_SIGNING_DUMMY //#define MYSENSORS_SIGNING_ATSHA204 +//#define MYSENSORS_SIGNING_ATSHA204SOFT // Define a suitable timeout for a signature verification session // Consider the turnaround from a nonce being generated to a signed message being received @@ -58,6 +59,33 @@ typedef class MySigningDriverDummy MySigningDriverClass; typedef class MySigningDriverAtsha204 MySigningDriverClass; #endif +#ifdef MYSENSORS_SIGNING_ATSHA204SOFT +// Key to use for HMAC calculation +static uint8_t hmacKey[32] = { +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, +0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +}; + +// Pick an unconnected analog pin for RANDOMSEED_PIN +#ifdef MYSENSORS_SENSOR +#define RANDOMSEED_PIN 7 //A7 +#endif + +#ifdef MYSENSORS_SERIAL_GATEWAY +#define RANDOMSEED_PIN 7 //A7 +#endif + +#ifdef MYSENSORS_ETHERNET_MQTT_GATEWAY +#define RANDOMSEED_PIN 7 //A7 +#endif + +#include "MySigningDriverAtsha204Soft.h" +#define SIGNING_IDENTIFIER (1) // SHA256-based HMAC (ATSHA204 specific) +typedef class MySigningDriverAtsha204Soft MySigningDriverClass; +#endif + /*** * Enable/Disable debug logging */ diff --git a/libraries/MySensors/MySigningDriverAtsha204Soft.cpp b/libraries/MySensors/MySigningDriverAtsha204Soft.cpp new file mode 100644 index 0000000..aaff71f --- /dev/null +++ b/libraries/MySensors/MySigningDriverAtsha204Soft.cpp @@ -0,0 +1,225 @@ +/* + ATSHA204 emulated signing backend. The emulated ATSHA204 implementation offers pseudo random + number generation and HMAC-SHA256 authentication compatible with a "physical" ATSHA204. + NOTE: Key is stored in clear text in the Arduino firmware. Therefore, the use of this back-end + could compromise the key used in the signed message infrastructure if device is lost and its memory + dumped. + + Created by Patrick "Anticimex" Fallberg +*/ +#include "MySigningDriver.h" +#include "MySigningDriverAtsha204Soft.h" +#include "sha256.h" + +#ifdef MYSENSORS_SIGNING_ATSHA204SOFT +// Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) +//#define DEBUG_ATSHASOFT_SIGNING + +#ifdef DEBUG_ATSHASOFT_SIGNING +#define DEBUG_ATSHASOFT_PRINTLN(args) Serial.println(args) +#else +#define DEBUG_ATSHASOFT_PRINTLN(args) +#endif + +#ifdef DEBUG_ATSHASOFT_SIGNING +static void DEBUG_ATSHASOFT_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) +{ + int i; + Serial.println(str); + for (int i=0; i timestamp + VERIFICATION_TIMEOUT_MS) { + DEBUG_ATSHASOFT_PRINTLN("Verification timeout"); + // Purge nonce + memset(current_nonce, 0xAA, 32); + verification_ongoing = false; + return false; + } + } + return true; +} + +bool MySigningDriverAtsha204Soft::putNonce(MyMessage &msg) { + if (mGetLength(msg) != MAX_PAYLOAD) { + DEBUG_ATSHASOFT_PRINTLN("Incoming nonce with incorrect size"); + return false; // We require as big nonce as possible + } + + if (((uint8_t*)msg.getCustom())[0] != SIGNING_IDENTIFIER) { + DEBUG_ATSHASOFT_PRINTLN("Incorrect signing identifier"); + return false; + } + + memcpy(current_nonce, (uint8_t*)msg.getCustom(), MAX_PAYLOAD); + return true; +} + +bool MySigningDriverAtsha204Soft::signMsg(MyMessage &msg) { + // If we cannot fit any signature in the message, refuse to sign it + if (mGetLength(msg) > MAX_PAYLOAD-2) { + DEBUG_ATSHASOFT_PRINTLN("Cannot fit any signature to this message"); + return false; + } + + // Calculate signature of message + mSetSigned(msg, 1); // make sure signing flag is set before signature is calculated + DEBUG_ATSHASOFT_PRINTBUF("Message to sign:", (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); + if (!calculateSignature(msg)) { + DEBUG_ATSHASOFT_PRINTLN("Failed to calculate signature"); + mSetSigned(msg, 0); // make sure signing flag is truthful + return false; + } + + // Transfer as much signature data as the remaining space in the message permits + memcpy(&msg.data[mGetLength(msg)], hmac, MAX_PAYLOAD-mGetLength(msg)); + + return true; +} + +bool MySigningDriverAtsha204Soft::verifyMsg(MyMessage &msg) { + if (!verification_ongoing) { + DEBUG_ATSHASOFT_PRINTLN("No active verification session"); + return false; + } else { + // Make sure we have not expired + if (!checkTimer()) { + return false; + } + + verification_ongoing = false; + + if (msg.data[mGetLength(msg)] != SIGNING_IDENTIFIER) { + DEBUG_ATSHASOFT_PRINTLN("Incorrect signing identifier"); + return false; + } + + DEBUG_ATSHASOFT_PRINTBUF("Message to verify:", (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); + DEBUG_ATSHASOFT_PRINTBUF("Signature in message:", (uint8_t*)&msg.data[mGetLength(msg)], MAX_PAYLOAD-mGetLength(msg)); + + // Get signature of message + if (!calculateSignature(msg)) { + DEBUG_ATSHASOFT_PRINTLN("Failed to calculate signature"); + return false; + } + + // Compare the caluclated signature with the provided signature + if (memcmp(&msg.data[mGetLength(msg)], hmac, MAX_PAYLOAD-mGetLength(msg))) { + DEBUG_ATSHASOFT_PRINTBUF("Signature bad. Calculated signature:", hmac, MAX_PAYLOAD-mGetLength(msg)); + return false; + } else { + DEBUG_ATSHASOFT_PRINTLN("Signature ok"); + return true; + } + } +} + +// Helper to calculate signature of msg (returned in rx_buffer[SHA204_BUFFER_POS_DATA]) +bool MySigningDriverAtsha204Soft::calculateSignature(MyMessage &msg) { + memset(temp_message, 0, 32); + memcpy(temp_message, (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); + + // ATSHA204 calculates the HMAC with a PSK and a SHA256 digest of the following data: + // 32 bytes zeroes + // 32 bytes digest, + // 1 byte OPCODE (0x11) + // 1 byte Mode (0x04) + // 2 bytes SlotID (0x0000) + // 11 bytes zeroes + // SN[8] (0xEE) + // 4 bytes zeroes + // SN[0:1] (0x0123) + // 2 bytes zeroes + + // The digest is calculated as a SHA256 digest of the following: + // 32 bytes message + // 1 byte OPCODE (0x15) + // 1 byte param1 (0x02) + // 2 bytes param2 (0x0800) + // SN[8] (0xEE) + // SN[0:1] (0x0123) + // 25 bytes zeroes + // 32 bytes nonce + + // Calculate message digest first + Sha256.init(); + for (int i=0; i<32; i++) Sha256.write(temp_message[i]); + Sha256.write(0x15); // OPCODE + Sha256.write(0x02); // param1 + Sha256.write(0x08); // param2(1) + Sha256.write(0x00); // param2(2) + Sha256.write(0xEE); // SN[8] + Sha256.write(0x01); // SN[0] + Sha256.write(0x23); // SN[1] + for (int i=0; i<25; i++) Sha256.write(0x00); + for (int i=0; i<32; i++) Sha256.write(current_nonce[i]); + // Purge nonce when used + memset(current_nonce, 0xAA, 32); + memcpy(temp_message, Sha256.result(), 32); + + // Feed "message" to HMAC calculator + Sha256.initHmac(hmacKey,32); // Set the key to use + for (int i=0; i<32; i++) Sha256.write(0x00); // 32 bytes zeroes + for (int i=0; i<32; i++) Sha256.write(temp_message[i]); // 32 bytes digest + Sha256.write(0x11); // OPCODE + Sha256.write(0x04); // Mode + Sha256.write(0x00); // SlotID(1) + Sha256.write(0x00); // SlotID(2) + for (int i=0; i<11; i++) Sha256.write(0x00); // 11 bytes zeroes + Sha256.write(0xEE); // SN[8] + for (int i=0; i<4; i++) Sha256.write(0x00); // 4 bytes zeroes + Sha256.write(0x01); // SN[0] + Sha256.write(0x23); // SN[1] + for (int i=0; i<2; i++) Sha256.write(0x00); // 2 bytes zeroes + + hmac = Sha256.resultHmac(); + + // Overwrite the first byte in the signature with the signing identifier + hmac[0] = SIGNING_IDENTIFIER; + + DEBUG_ATSHASOFT_PRINTBUF("HMAC:", hmac, 32); + return true; +} +#endif diff --git a/libraries/MySensors/MySigningDriverAtsha204Soft.h b/libraries/MySensors/MySigningDriverAtsha204Soft.h new file mode 100644 index 0000000..16d8d3e --- /dev/null +++ b/libraries/MySensors/MySigningDriverAtsha204Soft.h @@ -0,0 +1,43 @@ +/* + ATSHA204 emulated signing backend. The emulated ATSHA204 implementation offers pseudo random + number generation and HMAC-SHA256 authentication compatible with a "physical" ATSHA204. + NOTE: Key is stored in clear text in the Arduino firmware. Therefore, the use of this back-end + could compromise the key used in the signed message infrastructure if device is lost and its memory + dumped. + + Created by Patrick "Anticimex" Fallberg +*/ +#ifndef MySigningDriverHmac256Soft_h +#define MySigningDriverHmac256Soft_h + +#include "MyConfig.h" +#include "MySigningDriver.h" +#include "utility/ATSHA204.h" +#include + +// This implementation is the pure software variant of the ATSHA204. +// It is designed to work fully compliant with nodes using ATSHA204 in the network +// and therefore uses the same signing identifier as ATSHA204. +// Because it is completly software based, the quality of the generated random numbers +// is weaker though. Random numbers are generated using the Arduino library and seed +// is sampled from an analog pin. This pin should unconnected in the hardware. +// The pin is selected using RANDOMSEED_PIN in MyConfig.h. +class MySigningDriverAtsha204Soft : public MySigningDriver +{ +public: + MySigningDriverAtsha204Soft(); + bool getNonce(MyMessage &msg); + bool checkTimer(void); + bool putNonce(MyMessage &msg); + bool signMsg(MyMessage &msg); + bool verifyMsg(MyMessage &msg); +private: + unsigned long timestamp; + bool verification_ongoing; + uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH]; + uint8_t temp_message[32]; + uint8_t* hmac; + bool calculateSignature(MyMessage &msg); +}; + +#endif diff --git a/libraries/MySensors/utility/sha256.cpp b/libraries/MySensors/utility/sha256.cpp new file mode 100644 index 0000000..8434499 --- /dev/null +++ b/libraries/MySensors/utility/sha256.cpp @@ -0,0 +1,167 @@ +#include +#include +#include +#include "sha256.h" + +uint32_t sha256K[] PROGMEM = { + 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, + 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, + 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, + 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, + 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, + 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, + 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, + 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 +}; + +#define BUFFER_SIZE 64 + +uint8_t sha256InitState[] PROGMEM = { + 0x67,0xe6,0x09,0x6a, // H0 + 0x85,0xae,0x67,0xbb, // H1 + 0x72,0xf3,0x6e,0x3c, // H2 + 0x3a,0xf5,0x4f,0xa5, // H3 + 0x7f,0x52,0x0e,0x51, // H4 + 0x8c,0x68,0x05,0x9b, // H5 + 0xab,0xd9,0x83,0x1f, // H6 + 0x19,0xcd,0xe0,0x5b // H7 +}; + +void Sha256Class::init(void) { + memcpy_P(state.b,sha256InitState,32); + byteCount = 0; + bufferOffset = 0; +} + +uint32_t Sha256Class::ror32(uint32_t number, uint8_t bits) { + return ((number << (32-bits)) | (number >> bits)); +} + +void Sha256Class::hashBlock() { + uint8_t i; + uint32_t a,b,c,d,e,f,g,h,t1,t2; + + a=state.w[0]; + b=state.w[1]; + c=state.w[2]; + d=state.w[3]; + e=state.w[4]; + f=state.w[5]; + g=state.w[6]; + h=state.w[7]; + + for (i=0; i<64; i++) { + if (i>=16) { + t1 = buffer.w[i&15] + buffer.w[(i-7)&15]; + t2 = buffer.w[(i-2)&15]; + t1 += ror32(t2,17) ^ ror32(t2,19) ^ (t2>>10); + t2 = buffer.w[(i-15)&15]; + t1 += ror32(t2,7) ^ ror32(t2,18) ^ (t2>>3); + buffer.w[i&15] = t1; + } + t1 = h; + t1 += ror32(e,6) ^ ror32(e,11) ^ ror32(e,25); // ∑1(e) + t1 += g ^ (e & (g ^ f)); // Ch(e,f,g) + t1 += pgm_read_dword(sha256K+i); // Ki + t1 += buffer.w[i&15]; // Wi + t2 = ror32(a,2) ^ ror32(a,13) ^ ror32(a,22); // ∑0(a) + t2 += ((b & c) | (a & (b | c))); // Maj(a,b,c) + h=g; g=f; f=e; e=d+t1; d=c; c=b; b=a; a=t1+t2; + } + state.w[0] += a; + state.w[1] += b; + state.w[2] += c; + state.w[3] += d; + state.w[4] += e; + state.w[5] += f; + state.w[6] += g; + state.w[7] += h; +} + +void Sha256Class::addUncounted(uint8_t data) { + buffer.b[bufferOffset ^ 3] = data; + bufferOffset++; + if (bufferOffset == BUFFER_SIZE) { + hashBlock(); + bufferOffset = 0; + } +} + +void Sha256Class::write(uint8_t data) { + ++byteCount; + addUncounted(data); +} + +void Sha256Class::pad() { + // Implement SHA-256 padding (fips180-2 §5.1.1) + + // Pad with 0x80 followed by 0x00 until the end of the block + addUncounted(0x80); + while (bufferOffset != 56) addUncounted(0x00); + + // Append length in the last 8 bytes + addUncounted(0); // We're only using 32 bit lengths + addUncounted(0); // But SHA-1 supports 64 bit lengths + addUncounted(0); // So zero pad the top bits + addUncounted(byteCount >> 29); // Shifting to multiply by 8 + addUncounted(byteCount >> 21); // as SHA-1 supports bitstreams as well as + addUncounted(byteCount >> 13); // byte. + addUncounted(byteCount >> 5); + addUncounted(byteCount << 3); +} + + +uint8_t* Sha256Class::result(void) { + // Pad to complete the last block + pad(); + + // Swap byte order back + for (int i=0; i<8; i++) { + uint32_t a,b; + a=state.w[i]; + b=a<<24; + b|=(a<<8) & 0x00ff0000; + b|=(a>>8) & 0x0000ff00; + b|=a>>24; + state.w[i]=b; + } + + // Return pointer to hash (20 characters) + return state.b; +} + +#define HMAC_IPAD 0x36 +#define HMAC_OPAD 0x5c + +uint8_t keyBuffer[BLOCK_LENGTH]; // K0 in FIPS-198a +uint8_t innerHash[HASH_LENGTH]; + +void Sha256Class::initHmac(const uint8_t* key, int keyLength) { + uint8_t i; + memset(keyBuffer,0,BLOCK_LENGTH); + if (keyLength > BLOCK_LENGTH) { + // Hash long keys + init(); + for (;keyLength--;) write(*key++); + memcpy(keyBuffer,result(),HASH_LENGTH); + } else { + // Block length keys are used as is + memcpy(keyBuffer,key,keyLength); + } + // Start inner hash + init(); + for (i=0; i + +#define HASH_LENGTH 32 +#define BLOCK_LENGTH 64 + +union _buffer { + uint8_t b[BLOCK_LENGTH]; + uint32_t w[BLOCK_LENGTH/4]; +}; +union _state { + uint8_t b[HASH_LENGTH]; + uint32_t w[HASH_LENGTH/4]; +}; + +class Sha256Class +{ + public: + void init(void); + void initHmac(const uint8_t* secret, int secretLength); + uint8_t* result(void); + uint8_t* resultHmac(void); + virtual void write(uint8_t); + private: + void pad(); + void addUncounted(uint8_t data); + void hashBlock(); + uint32_t ror32(uint32_t number, uint8_t bits); + _buffer buffer; + uint8_t bufferOffset; + _state state; + uint32_t byteCount; + uint8_t keyBuffer[BLOCK_LENGTH]; + uint8_t innerHash[HASH_LENGTH]; +}; + +#endif From 644eac1712d74f8f149ab57877253129a2546c6b Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 7 Feb 2015 13:49:08 +0100 Subject: [PATCH 045/137] Signing support implemented in the MySensors library The dummy signing driver backend is used. But with this commit all framework logic for managing signed messages in the MySensors ecosystem is implemented and enables more sophisticated signing backends to be added later on. For a sensor (or gateway) that require a gateway to send signed messages to it, add 'true' as the fifth argument to 'begin'. The gateway will automatically inform a node of it's signing requirements as soon as it receivs the nodes signing preference. It is important to understand that if the gateway require signing, it will in this implementation only require signing from nodes that require signing by the gateway. If the sensor requires signing from another node on the network which it communicates directly with, it needs to send 'true' in an internal message of type I_REQUEST_SIGNING. --- Bootloader/MyOtaBootloader.c | 6 ++ libraries/MySensors/MySensor.cpp | 99 +++++++++++++++++++++++++++++--- libraries/MySensors/MySensor.h | 13 ++++- 3 files changed, 109 insertions(+), 9 deletions(-) diff --git a/Bootloader/MyOtaBootloader.c b/Bootloader/MyOtaBootloader.c index fe4f24f..8dc1ef5 100644 --- a/Bootloader/MyOtaBootloader.c +++ b/Bootloader/MyOtaBootloader.c @@ -152,6 +152,12 @@ int main () { address(nc.nodeId); } + // Inform gateway that bootloader does not accept signed messages + msg.type = I_REQUEST_SIGNING; + mSetLength(msg, 1); + msg.data[0] = 0; + sendWrite(msg); + // Read settings from EEPROM eeprom_read_block((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(struct FirmwareConfig)); diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 7c8bff6..c227c0c 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -13,6 +13,10 @@ #define DISTANCE_INVALID (0xFF) +// Macros for manipulating signing requirement table +#define DO_SIGN(node) (doSign[node>>4]&(node%16)) +#define SET_SIGN(node) (doSign[node>>4]|=(node%16)) +#define CLEAR_SIGN(node) (doSign[node>>4]&=~(node%16)) // Inline function and macros static inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, uint8_t sensor, uint8_t command, uint8_t type, bool enableAck) { @@ -35,14 +39,17 @@ static inline bool isValidDistance( const uint8_t distance ) { MySensor::MySensor() { radio = (MyRFDriver*) new MyRFDriverClass(); + signer = (MySigningDriver*) new MySigningDriverClass(); } -void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId) { +void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId, bool requestSignatures) { Serial.begin(BAUD_RATE); repeaterMode = _repeaterMode; msgCallback = _msgCallback; failedTransmissions = 0; + requireSigning = requestSignatures; + // Only gateway should use node id 0 isGateway = _nodeId == 0; @@ -55,6 +62,8 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b eeprom_read_block((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); // Read latest received controller configuration from EEPROM eeprom_read_block((void*)&cc, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS, sizeof(ControllerConfig)); + // Read out the signing requirements from EEPROM + eeprom_read_block((void*)doSign, (void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, sizeof(doSign)); if (isGateway) { nc.distance = 0; @@ -137,6 +146,9 @@ void MySensor::setupNode() { // Send presentation for this radio node (attach present(NODE_SENSOR_ID, repeaterMode? S_ARDUINO_REPEATER_NODE : S_ARDUINO_NODE); + // Notify gateway (and possibly controller) about the signing preferences of this node + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(requireSigning)); + // Send a configuration exchange request to controller // Node sends parent node. Controller answers with latest node configuration // which is picked up in process() @@ -178,6 +190,19 @@ boolean MySensor::sendRoute(MyMessage &message) { return false; } + mSetVersion(message, PROTOCOL_VERSION); + + // If destination is known to require signed messages and we are the sender, sign this message unless it is an ACK or a signing handshake message + if (DO_SIGN(message.destination) && message.sender == nc.nodeId && !mGetAck(message) && mGetLength(msg) && + (mGetCommand(message) != C_INTERNAL || (message.type != I_GET_NONCE && message.type != I_GET_NONCE_RESPONSE && message.type != I_REQUEST_SIGNING))) { + if (!sign(message)) { + debug(PSTR("Message signing failed\n")); + return false; + } + // After this point, only the 'last' member of the message structure is allowed to be altered if the message has been signed, + // or signature will become invalid and the message rejected by the receiver + } else mSetSigned(message, 0); // Message is not supposed to be signed, make sure it is marked unsigned + if (dest == GATEWAY_ADDRESS || !repeaterMode) { // If destination is the gateway or if we aren't a repeater, let // our parent take care of the message @@ -240,14 +265,13 @@ boolean MySensor::sendRoute(MyMessage &message) { } boolean MySensor::sendWrite(uint8_t to, MyMessage &message) { - uint8_t length = mGetLength(message); + uint8_t length = mGetSigned(message) ? MAX_MESSAGE_LENGTH : mGetLength(message); message.last = nc.nodeId; - mSetVersion(message, PROTOCOL_VERSION); bool ok = radio->send(to, &message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length)); - debug(PSTR("send: %d-%d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d,st=%s:%s\n"), + debug(PSTR("send: %d-%d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d,sg=%d,st=%s:%s\n"), message.sender,message.last, to, message.destination, message.sensor, mGetCommand(message), message.type, - mGetPayloadType(message), mGetLength(message), to==BROADCAST_ADDRESS ? "bc" : (ok ? "ok":"fail"), message.getString(convBuf)); + mGetPayloadType(message), mGetLength(message), mGetSigned(message), to==BROADCAST_ADDRESS ? "bc" : (ok ? "ok":"fail"), message.getString(convBuf)); return ok; } @@ -290,12 +314,26 @@ boolean MySensor::process() { if (!radio->available(&to)) return false; + (void)signer->checkTimer(); // Manage signing timeout + uint8_t len = radio->receive((uint8_t *)&msg); + // Before processing message, reject unsigned messages if signing is required and check signature (if it is signed and addressed to us) + // Note that we do not care at all about any signature found if we do not require signing + if (requireSigning && msg.destination == nc.nodeId && mGetLength(msg) && + (mGetCommand(msg) != C_INTERNAL || (msg.type != I_GET_NONCE_RESPONSE && msg.type != I_GET_NONCE && msg.type != I_REQUEST_SIGNING))) { + if (!mGetSigned(msg)) return false; // Received an unsigned message but we do require signing. This message gets nowhere! + else if (!signer->verifyMsg(msg)) { + debug(PSTR("Message verification failed\n")); + return false; // This signed message has been tampered with! + } + } + // Add string termination, good if we later would want to print it. msg.data[mGetLength(msg)] = '\0'; - debug(PSTR("read: %d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d:%s\n"), - msg.sender, msg.last, msg.destination, msg.sensor, mGetCommand(msg), msg.type, mGetPayloadType(msg), mGetLength(msg), msg.getString(convBuf)); + debug(PSTR("read: %d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d,sg=%d:%s\n"), + msg.sender, msg.last, msg.destination, msg.sensor, mGetCommand(msg), msg.type, mGetPayloadType(msg), mGetLength(msg), mGetSigned(msg), msg.getString(convBuf)); + mSetSigned(msg,0); // Clear the sign-flag now as verification (and debug printing) is completed if(!(mGetVersion(msg) == PROTOCOL_VERSION)) { debug(PSTR("version: %d\n"),mGetVersion(msg)); @@ -349,6 +387,32 @@ boolean MySensor::process() { } } return false; + } else if (type == I_GET_NONCE) { + if (signer->getNonce(msg)) { + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_GET_NONCE_RESPONSE, false)); + } else { + return false; + } + } else if (type == I_REQUEST_SIGNING) { + if (msg.getBool()) { + // We received an indicator that the sender require us to sign all messages we send to it + SET_SIGN(msg.sender); + } else { + // We received an indicator that the sender does not require us to sign all messages we send to it + CLEAR_SIGN(msg.sender); + } + // Save updated table + eeprom_write_block((void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, (void*)doSign, sizeof(doSign)); + + // Inform sender about our preference if we are a gateway, but only require signing if the sender required signing + // We do not currently want a gateway to require signing from all nodes in a network just because it wants one node + // to sign it's messages + if (isGateway) { + if (requireSigning) + sendRoute(build(msg, nc.nodeId, msg.sender, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(requireSigning)); + else + sendRoute(build(msg, nc.nodeId, msg.sender, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(false)); + } } else if (sender == GATEWAY_ADDRESS) { bool isMetric; @@ -543,6 +607,27 @@ int8_t MySensor::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, ui return retVal; } +bool MySensor::sign(MyMessage &message) { + MyMessage msgNonce; + if (!sendRoute(build(msgNonce, nc.nodeId, message.destination, message.sensor, C_INTERNAL, I_GET_NONCE, false).set(""))) { + return false; + } else { + // We have to wait for the nonce to arrive before we can sign our original message + // Other messages could come in-between. We trust process() takes care of them + unsigned long enter = millis(); + while (millis() - enter < 5000) { + if (process()) { + if (getLastMessage().type == I_GET_NONCE_RESPONSE) { + // Proceed with signing if nonce has been received + if (signer->putNonce(getLastMessage()) && signer->signMsg(message)) return true; + break; + } + } + } + } + return false; +} + #ifdef DEBUG void MySensor::debugPrint(const char *fmt, ... ) { char fmtBuffer[300]; diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index c9e79a7..8541492 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -14,6 +14,7 @@ #include "Version.h" // Auto generated by bot #include "MyRFDriver.h" +#include "MySigningDriver.h" #include "MyConfig.h" #include "MyMessage.h" #include @@ -50,7 +51,8 @@ #define EEPROM_FIRMWARE_VERSION_ADDRESS (EEPROM_FIRMWARE_TYPE_ADDRESS+2) #define EEPROM_FIRMWARE_BLOCKS_ADDRESS (EEPROM_FIRMWARE_VERSION_ADDRESS+2) #define EEPROM_FIRMWARE_CRC_ADDRESS (EEPROM_FIRMWARE_BLOCKS_ADDRESS+2) -#define EEPROM_LOCAL_CONFIG_ADDRESS (EEPROM_FIRMWARE_CRC_ADDRESS+2) // First free address for sketch static configuration +#define EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS (EEPROM_FIRMWARE_CRC_ADDRESS+2) +#define EEPROM_LOCAL_CONFIG_ADDRESS (EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS+32) // First free address for sketch static configuration // Search for a new parent node after this many transmission failures #define SEARCH_FAILURES 5 @@ -86,9 +88,10 @@ class MySensor * @param nodeId The unique id (1-254) for this sensor. Default is AUTO(255) which means sensor tries to fetch an id from controller. * @param repeaterMode Activate repeater mode. This node will forward messages to other nodes in the radio network. Make sure to call process() regularly. Default in false * @param parentNodeId Use this to force node to always communicate with a certain parent node. Default is AUTO which means node automatically tries to find a parent. + * @param requestSignatures Set this to true if you want destination node to sign all messages sent to this node. Default is not to require signing. */ - void begin(void (* msgCallback)(const MyMessage &)=NULL, uint8_t nodeId=AUTO, boolean repeaterMode=false, uint8_t parentNodeId=AUTO); + void begin(void (* msgCallback)(const MyMessage &)=NULL, uint8_t nodeId=AUTO, boolean repeaterMode=false, uint8_t parentNodeId=AUTO, bool requestSignatures=false); /** * Return the nodes nodeId. @@ -238,10 +241,15 @@ class MySensor bool repeaterMode; bool autoFindParent; bool isGateway; + bool requireSigning; + uint16_t doSign[16]; // Bitfield indicating which sensors require signed communication + MyMessage msg; // Buffer for incoming messages. MyMessage ack; // Buffer for ack messages. MyRFDriver *radio; + + MySigningDriver *signer; void setupRepeaterMode(); void setupRadio(); @@ -264,6 +272,7 @@ class MySensor void addChildRoute(uint8_t childId, uint8_t route); void removeChildRoute(uint8_t childId); void internalSleep(unsigned long ms); + bool sign(MyMessage &message); }; #endif From cfc8d9f28a9c74e0854c4e41cf39d4f488c13364 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 7 Feb 2015 14:35:19 +0100 Subject: [PATCH 046/137] Added example sketch for a secure actuator The sketch closely resembles the RelayActuator example. The difference is that this sketch require gateway to sign all messages addressed to the actuator. --- .../SecureActuator/SecureActuator.ino | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 libraries/MySensors/examples/SecureActuator/SecureActuator.ino diff --git a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino new file mode 100644 index 0000000..c86ff49 --- /dev/null +++ b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino @@ -0,0 +1,57 @@ +// Example sketch showing how to securely control locks. +// This example will remember lock state even after power failure. + +#include +#include + +#ifndef MYSENSORS_SENSOR +#error Please switch to MYSENSORS_SENSOR in MyConfig.h +#endif + +#define LOCK_1 3 // Arduino Digital I/O pin number for first lock (second on pin+1 etc) +#define NOF_LOCKS 1 // Total number of attached locks +#define LOCK_LOCK 1 // GPIO value to write to lock attached lock +#define LOCK_UNLOCK 0 // GPIO value to write to unlock attached lock + +MySensor gw; + +void setup() +{ + // Initialize library and add callback for incoming messages (signing is required) + gw.begin(incomingMessage, AUTO, true, AUTO, true); + // Send the sketch version information to the gateway and Controller + gw.sendSketchInfo("Secure Lock", "1.0"); + + // Fetch lock status + for (int lock=1, pin=LOCK_1; lock<=NOF_LOCKS;lock++, pin++) { + // Register all locks to gw (they will be created as child devices) + gw.present(lock, S_LOCK, false); + // Then set lock pins in output mode + pinMode(pin, OUTPUT); + // Set lock to last known state (using eeprom storage) + digitalWrite(pin, gw.loadState(lock)?LOCK_LOCK:LOCK_UNLOCK); + } +} + + +void loop() +{ + // Alway process incoming messages whenever possible + gw.process(); +} + +void incomingMessage(const MyMessage &message) { + // We only expect one type of message from controller. But we better check anyway. + if (message.type==V_LOCK_STATUS && message.sensor<=NOF_LOCKS) { + // Change relay state + digitalWrite(message.sensor-1+LOCK_1, message.getBool()?LOCK_LOCK:LOCK_UNLOCK); + // Store state in eeprom + gw.saveState(message.sensor, message.getBool()); + // Write some debug info + Serial.print("Incoming change for lock:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getBool()); + } +} + From d7474a7b8d8711c5f6fa50709690f88b4667a5f5 Mon Sep 17 00:00:00 2001 From: Marcelo Aquino Date: Wed, 18 Feb 2015 11:15:54 -0200 Subject: [PATCH 047/137] fix ifdef for MYSENSORS_ETHERNET_MQTT_GATEWAY --- libraries/MySensors/MyConfig.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 0ffab4e..ecae372 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -50,7 +50,7 @@ typedef class MySigningDriverDummy MySigningDriverClass; #define ATSHA204_PIN 17 //A3 #endif -#ifdef MYSENSORS_ETHERNET_MQTT_GATEWAY +#if defined(MYSENSORS_ETHERNET_GATEWAY) || defined(MYSENSORS_MQTT_GATEWAY) #define ATSHA204_PIN 17 //A3 #endif @@ -77,7 +77,7 @@ static uint8_t hmacKey[32] = { #define RANDOMSEED_PIN 7 //A7 #endif -#ifdef MYSENSORS_ETHERNET_MQTT_GATEWAY +#if defined(MYSENSORS_ETHERNET_GATEWAY) || defined(MYSENSORS_MQTT_GATEWAY) #define RANDOMSEED_PIN 7 //A7 #endif From 729cf8da5d4ad9eeeb99736e390e5dbceef6b113 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 18 Feb 2015 23:40:58 +0100 Subject: [PATCH 048/137] Bugifx: GW should not send presentation --- libraries/MySensors/MySensor.cpp | 38 +++++++++++++++----------------- libraries/MySensors/MySensor.h | 1 - 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 7c8bff6..3a74892 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -49,7 +49,9 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b if (repeaterMode) { setupRepeaterMode(); } - setupRadio(); + + // Setup radio + radio->init(); // Read settings from eeprom eeprom_read_block((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); @@ -92,21 +94,10 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b requestNodeId(); } - if (!isGateway) { - debug(PSTR("%s started, id=%d, parent=%d, distance=%d\n"), repeaterMode?"repeater":"sensor", nc.nodeId, nc.parentNodeId, nc.distance); - } + setupNode(); - // If we got an id, set this node to use it - if (nc.nodeId != AUTO) { - setupNode(); - // Wait configuration reply. - wait(2000); - } -} + debug(PSTR("%s started, id=%d, parent=%d, distance=%d\n"), isGateway?"gateway":(repeaterMode?"repeater":"sensor"), nc.nodeId, nc.parentNodeId, nc.distance); -void MySensor::setupRadio() { - failedTransmissions = 0; - radio->init(); } void MySensor::setupRepeaterMode(){ @@ -134,13 +125,20 @@ void MySensor::setupNode() { // Open reading pipe for messages directed to this node (set write pipe to same) radio->setAddress(nc.nodeId); - // Send presentation for this radio node (attach - present(NODE_SENSOR_ID, repeaterMode? S_ARDUINO_REPEATER_NODE : S_ARDUINO_NODE); + // Present node and request config + if (!isGateway && nc.nodeId != AUTO) { + // Send presentation for this radio node (attach + present(NODE_SENSOR_ID, repeaterMode? S_ARDUINO_REPEATER_NODE : S_ARDUINO_NODE); + + // Send a configuration exchange request to controller + // Node sends parent node. Controller answers with latest node configuration + // which is picked up in process() + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_CONFIG, false).set(nc.parentNodeId)); + + // Wait configuration reply. + wait(2000); + } - // Send a configuration exchange request to controller - // Node sends parent node. Controller answers with latest node configuration - // which is picked up in process() - sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_CONFIG, false).set(nc.parentNodeId)); } void MySensor::findParentNode() { diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index c9e79a7..2e4af82 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -244,7 +244,6 @@ class MySensor MyRFDriver *radio; void setupRepeaterMode(); - void setupRadio(); boolean sendWrite(uint8_t dest, MyMessage &message); private: From e25f4974b226174d49f1e2213cd57da3b85418cc Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 19 Feb 2015 09:09:38 +0100 Subject: [PATCH 049/137] Save some bytes by removing new when initalizing drivers --- libraries/MySensors/MySensor.cpp | 28 +++++++++++++--------------- libraries/MySensors/MySensor.h | 4 ++-- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 120f7ef..9466e5e 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -38,8 +38,6 @@ static inline bool isValidDistance( const uint8_t distance ) { } MySensor::MySensor() { - radio = (MyRFDriver*) new MyRFDriverClass(); - signer = (MySigningDriver*) new MySigningDriverClass(); } @@ -58,7 +56,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b } // Setup radio - radio->init(); + radio.init(); // Read settings from eeprom eeprom_read_block((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); @@ -124,7 +122,7 @@ ControllerConfig MySensor::getConfig() { void MySensor::requestNodeId() { debug(PSTR("req node id\n")); - radio->setAddress(nc.nodeId); + radio.setAddress(nc.nodeId); build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_ID_REQUEST, false).set(""); sendWrite(nc.parentNodeId, msg); wait(2000); @@ -132,7 +130,7 @@ void MySensor::requestNodeId() { void MySensor::setupNode() { // Open reading pipe for messages directed to this node (set write pipe to same) - radio->setAddress(nc.nodeId); + radio.setAddress(nc.nodeId); // Present node and request config if (!isGateway && nc.nodeId != AUTO) { @@ -264,7 +262,7 @@ boolean MySensor::sendRoute(MyMessage &message) { boolean MySensor::sendWrite(uint8_t to, MyMessage &message) { uint8_t length = mGetSigned(message) ? MAX_MESSAGE_LENGTH : mGetLength(message); message.last = nc.nodeId; - bool ok = radio->send(to, &message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length)); + bool ok = radio.send(to, &message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length)); debug(PSTR("send: %d-%d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d,sg=%d,st=%s:%s\n"), message.sender,message.last, to, message.destination, message.sensor, mGetCommand(message), message.type, @@ -308,19 +306,19 @@ void MySensor::requestTime(void (* _timeCallback)(unsigned long)) { boolean MySensor::process() { uint8_t to = 0; - if (!radio->available(&to)) + if (!radio.available(&to)) return false; - (void)signer->checkTimer(); // Manage signing timeout + (void)signer.checkTimer(); // Manage signing timeout - uint8_t len = radio->receive((uint8_t *)&msg); + uint8_t len = radio.receive((uint8_t *)&msg); // Before processing message, reject unsigned messages if signing is required and check signature (if it is signed and addressed to us) // Note that we do not care at all about any signature found if we do not require signing if (requireSigning && msg.destination == nc.nodeId && mGetLength(msg) && (mGetCommand(msg) != C_INTERNAL || (msg.type != I_GET_NONCE_RESPONSE && msg.type != I_GET_NONCE && msg.type != I_REQUEST_SIGNING))) { if (!mGetSigned(msg)) return false; // Received an unsigned message but we do require signing. This message gets nowhere! - else if (!signer->verifyMsg(msg)) { + else if (!signer.verifyMsg(msg)) { debug(PSTR("Message verification failed\n")); return false; // This signed message has been tampered with! } @@ -385,7 +383,7 @@ boolean MySensor::process() { } return false; } else if (type == I_GET_NONCE) { - if (signer->getNonce(msg)) { + if (signer.getNonce(msg)) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_GET_NONCE_RESPONSE, false)); } else { return false; @@ -541,7 +539,7 @@ void MySensor::internalSleep(unsigned long ms) { void MySensor::sleep(unsigned long ms) { // Let serial prints finish (debug, log etc) Serial.flush(); - radio->powerDown(); + radio.powerDown(); pinIntTrigger = 0; internalSleep(ms); } @@ -561,7 +559,7 @@ bool MySensor::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { // Let serial prints finish (debug, log etc) bool pinTriggeredWakeup = true; Serial.flush(); - radio->powerDown(); + radio.powerDown(); attachInterrupt(interrupt, wakeUp, mode); if (ms>0) { pinIntTrigger = 0; @@ -580,7 +578,7 @@ bool MySensor::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { int8_t MySensor::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) { int8_t retVal = 1; Serial.flush(); // Let serial prints finish (debug, log etc) - radio->powerDown(); + radio.powerDown(); attachInterrupt(interrupt1, wakeUp, mode1); attachInterrupt(interrupt2, wakeUp2, mode2); if (ms>0) { @@ -616,7 +614,7 @@ bool MySensor::sign(MyMessage &message) { if (process()) { if (getLastMessage().type == I_GET_NONCE_RESPONSE) { // Proceed with signing if nonce has been received - if (signer->putNonce(getLastMessage()) && signer->signMsg(message)) return true; + if (signer.putNonce(getLastMessage()) && signer.signMsg(message)) return true; break; } } diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index b995aae..7c6405e 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -247,9 +247,9 @@ class MySensor MyMessage msg; // Buffer for incoming messages. MyMessage ack; // Buffer for ack messages. - MyRFDriver *radio; + MyRFDriverClass radio; - MySigningDriver *signer; + MySigningDriverClass signer; void setupRepeaterMode(); boolean sendWrite(uint8_t dest, MyMessage &message); From 8274188b43bf3b68099bc71c1058ac8952fb6f19 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 19 Feb 2015 09:15:50 +0100 Subject: [PATCH 050/137] Use eeprom_update_* when writing to EEPROM Saves a few bytes and minimizes the number of write cycles. --- libraries/MySensors/MySensor.cpp | 44 ++++++++++++-------------------- 1 file changed, 17 insertions(+), 27 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 9466e5e..725572a 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -76,11 +76,9 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b autoFindParent = _parentNodeId == AUTO; if (!autoFindParent) { - if (_parentNodeId != nc.parentNodeId) { - nc.parentNodeId = _parentNodeId; - // Save static parent id in eeprom (used by bootloader) - eeprom_write_byte((uint8_t*)EEPROM_PARENT_NODE_ID_ADDRESS, _parentNodeId); - } + nc.parentNodeId = _parentNodeId; + // Save static parent id in eeprom (used by bootloader) + eeprom_update_byte((uint8_t*)EEPROM_PARENT_NODE_ID_ADDRESS, _parentNodeId); // We don't actually know the distance to gw here. Let's pretend it is 1. // If the current node is also repeater, be aware of this. nc.distance = 1; @@ -93,7 +91,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b // Set static id nc.nodeId = _nodeId; // Save static id in eeprom - eeprom_write_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, _nodeId); + eeprom_update_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, _nodeId); } // Try to fetch node-id from gateway @@ -375,8 +373,8 @@ boolean MySensor::process() { // Found a neighbor closer to GW than previously found nc.distance = distance; nc.parentNodeId = msg.sender; - eeprom_write_byte((uint8_t*)EEPROM_PARENT_NODE_ID_ADDRESS, nc.parentNodeId); - eeprom_write_byte((uint8_t*)EEPROM_DISTANCE_ADDRESS, nc.distance); + eeprom_update_byte((uint8_t*)EEPROM_PARENT_NODE_ID_ADDRESS, nc.parentNodeId); + eeprom_update_byte((uint8_t*)EEPROM_DISTANCE_ADDRESS, nc.distance); debug(PSTR("new parent=%d, d=%d\n"), nc.parentNodeId, nc.distance); } } @@ -397,7 +395,7 @@ boolean MySensor::process() { CLEAR_SIGN(msg.sender); } // Save updated table - eeprom_write_block((void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, (void*)doSign, sizeof(doSign)); + eeprom_update_block((void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, (void*)doSign, sizeof(doSign)); // Inform sender about our preference if we are a gateway, but only require signing if the sender required signing // We do not currently want a gateway to require signing from all nodes in a network just because it wants one node @@ -425,17 +423,15 @@ boolean MySensor::process() { } setupNode(); // Write id to EEPROM - eeprom_write_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, nc.nodeId); + eeprom_update_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, nc.nodeId); debug(PSTR("id=%d\n"), nc.nodeId); } } else if (type == I_CONFIG) { // Pick up configuration from controller (currently only metric/imperial) // and store it in eeprom if changed isMetric = msg.getString()[0] == 'M' ; - if (cc.isMetric != isMetric) { - cc.isMetric = isMetric; - eeprom_write_byte((uint8_t*)EEPROM_CONTROLLER_CONFIG_ADDRESS, isMetric); - } + cc.isMetric = isMetric; + eeprom_update_byte((uint8_t*)EEPROM_CONTROLLER_CONFIG_ADDRESS, isMetric); } else if (type == I_CHILDREN) { if (repeaterMode && msg.getString()[0] == 'C') { // Clears child relay data for this node @@ -445,8 +441,8 @@ boolean MySensor::process() { removeChildRoute(i); } while (i--); // Clear parent node id & distance to gw - eeprom_write_byte((uint8_t*)EEPROM_PARENT_NODE_ID_ADDRESS, 0xFF); - eeprom_write_byte((uint8_t*)EEPROM_DISTANCE_ADDRESS, 0xFF); + eeprom_update_byte((uint8_t*)EEPROM_PARENT_NODE_ID_ADDRESS, 0xFF); + eeprom_update_byte((uint8_t*)EEPROM_DISTANCE_ADDRESS, 0xFF); // Find parent node findParentNode(); sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_CHILDREN,false).set("")); @@ -487,26 +483,20 @@ MyMessage& MySensor::getLastMessage() { } void MySensor::saveState(uint8_t pos, uint8_t value) { - if (loadState(pos) != value) { - eeprom_write_byte((uint8_t*)(EEPROM_LOCAL_CONFIG_ADDRESS+pos), value); - } + eeprom_update_byte((uint8_t*)(EEPROM_LOCAL_CONFIG_ADDRESS+pos), value); } uint8_t MySensor::loadState(uint8_t pos) { return eeprom_read_byte((uint8_t*)(EEPROM_LOCAL_CONFIG_ADDRESS+pos)); } void MySensor::addChildRoute(uint8_t childId, uint8_t route) { - if (childNodeTable[childId] != route) { - childNodeTable[childId] = route; - eeprom_write_byte((uint8_t*)EEPROM_ROUTES_ADDRESS+childId, route); - } + childNodeTable[childId] = route; + eeprom_update_byte((uint8_t*)EEPROM_ROUTES_ADDRESS+childId, route); } void MySensor::removeChildRoute(uint8_t childId) { - if (childNodeTable[childId] != 0xff) { - childNodeTable[childId] = 0xff; - eeprom_write_byte((uint8_t*)EEPROM_ROUTES_ADDRESS+childId, 0xff); - } + childNodeTable[childId] = 0xff; + eeprom_update_byte((uint8_t*)EEPROM_ROUTES_ADDRESS+childId, 0xff); } uint8_t MySensor::getChildRoute(uint8_t childId) { From 85501622355a5b926c537c7b0aeb7770bc41848a Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 19 Feb 2015 11:22:36 +0100 Subject: [PATCH 051/137] Slim down dummy signing driver. --- libraries/MySensors/MySigningDriverDummy.cpp | 81 +------------------- libraries/MySensors/MySigningDriverDummy.h | 11 +-- 2 files changed, 6 insertions(+), 86 deletions(-) diff --git a/libraries/MySensors/MySigningDriverDummy.cpp b/libraries/MySensors/MySigningDriverDummy.cpp index 51d418f..f5bac3f 100644 --- a/libraries/MySensors/MySigningDriverDummy.cpp +++ b/libraries/MySensors/MySigningDriverDummy.cpp @@ -36,51 +36,17 @@ static void DEBUG_DUMMY_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) #endif MySigningDriverDummy::MySigningDriverDummy() : MySigningDriver() { - verification_ongoing = false; - current_nonce = 0; } bool MySigningDriverDummy::getNonce(MyMessage &msg) { - uint8_t nonce_buf[2]; - nonce_buf[0] = SIGNING_IDENTIFIER; - // This is normally a buffer but for our minimal driver we use a single byte - // We at least use a new nonce for every session - nonce_buf[1] = ++current_nonce; - msg.set(nonce_buf, 2); - verification_ongoing = true; - timestamp = millis(); // Set timestamp to determine when to purge nonce - // Be a little fancy to handle turnover (prolong the time allowed to timeout after turnover) - // Note that if message is "too" quick, and arrives before turnover, it will be rejected - // but this is consider such a rare case that it is accepted and rejects are 'safe' - if (timestamp + VERIFICATION_TIMEOUT_MS < millis()) timestamp = 0; return true; } bool MySigningDriverDummy::checkTimer() { - if (verification_ongoing) { - if (millis() < timestamp || millis() > timestamp + VERIFICATION_TIMEOUT_MS) { - DEBUG_DUMMY_PRINTLN("Verification timeout"); - // Purge nonce - current_nonce = 0; // purge nonce when used - verification_ongoing = false; - return false; - } - } return true; } bool MySigningDriverDummy::putNonce(MyMessage &msg) { - if (mGetLength(msg) != 2) { - DEBUG_DUMMY_PRINTLN("Incoming nonce with incorrect size"); - return false; // We require a signing identifier and a 1byte nonce - } - - if (((uint8_t*)msg.getCustom())[0] != SIGNING_IDENTIFIER) { - DEBUG_DUMMY_PRINTLN("Incorrect signing identifier"); - return false; - } - - current_nonce = ((uint8_t*)msg.getCustom())[1]; return true; } @@ -90,54 +56,15 @@ bool MySigningDriverDummy::signMsg(MyMessage &msg) { DEBUG_DUMMY_PRINTLN("Cannot fit any signature to this message"); return false; } - - // Calculate signature of message mSetSigned(msg, 1); // make sure signing flag is set before signature is calculated - DEBUG_DUMMY_PRINTBUF("Message to sign:", (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); - uint8_t signature = msg.data[0] ^ current_nonce; msg.data[mGetLength(msg)] = SIGNING_IDENTIFIER; // Add signing identifier - msg.data[mGetLength(msg)+1] = signature; - current_nonce = 0; // purge nonce when used return true; } bool MySigningDriverDummy::verifyMsg(MyMessage &msg) { - if (!verification_ongoing) { - DEBUG_DUMMY_PRINTLN("No active verification session"); - return false; - } else { - // Make sure we have not expired - if (!checkTimer()) { - return false; - } - - verification_ongoing = false; - - if (msg.data[mGetLength(msg)] != SIGNING_IDENTIFIER) { - DEBUG_DUMMY_PRINTLN("Incorrect signing identifier"); - return false; - } - - DEBUG_DUMMY_PRINTBUF("Message to verify:", (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); - DEBUG_DUMMY_PRINTBUF("Signature in message:", (uint8_t*)&msg.data[mGetLength(msg)], 2); - - // The dummy signing is the nonce XOR the first payload byte, - // so we "verify" by redoing that calculation with the nonce we transmitted - // Message without a payload this implementation always accepts as signed and messages that cannot - // fit a signature are also accepted as signed - if (mGetLength(msg) && mGetLength(msg) < MAX_PAYLOAD-2) { - uint8_t signature = msg.data[0] ^ current_nonce; - if (msg.data[mGetLength(msg)+1] != signature) { - DEBUG_DUMMY_PRINTBUF("Signature bad. Calculated signature:", &signature, 1); - return false; - } else { - DEBUG_DUMMY_PRINTLN("Signature ok"); - return true; - } - } else { - DEBUG_DUMMY_PRINTLN("No signature in message"); - return false; - } - } + if (msg.data[mGetLength(msg)] != SIGNING_IDENTIFIER) + return false; + else + return true; } #endif diff --git a/libraries/MySensors/MySigningDriverDummy.h b/libraries/MySensors/MySigningDriverDummy.h index 74b88a6..bf5ee81 100644 --- a/libraries/MySensors/MySigningDriverDummy.h +++ b/libraries/MySensors/MySigningDriverDummy.h @@ -10,11 +10,8 @@ #include "MySigningDriver.h" #include -// The dummy signing driver implements the most rudimentary form of signing -// No pre-shared key is used, nonce is simply incremeted each turn and signature -// is only calculated on the fist byte using data XOR nonce. -// This driver is intended for library debugging and sensor network integrity -// verification (signed messages will force the radio to transmit all 32 bytes of data). +// The dummy signing driver that can be used for nodes +// not requiring signing // It does check SIGNING_IDENTIFIER byte to avoid illegal mixing of signing back-ends in // the network (as seen by this node) and it does verify proper execution order on the API. // The dummy driver rejects all other back-ends. @@ -27,10 +24,6 @@ public: bool putNonce(MyMessage &msg); bool signMsg(MyMessage &msg); bool verifyMsg(MyMessage &msg); -private: - unsigned long timestamp; - bool verification_ongoing; - uint8_t current_nonce; }; #endif From 70b476ede4a5d32fad992b8c7b5ef7fe73397420 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 19 Feb 2015 13:47:45 +0100 Subject: [PATCH 052/137] Bugfix: setVersion missing in sendWrite --- libraries/MySensors/MySensor.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 725572a..149f3d8 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -258,6 +258,7 @@ boolean MySensor::sendRoute(MyMessage &message) { } boolean MySensor::sendWrite(uint8_t to, MyMessage &message) { + mSetVersion(message, PROTOCOL_VERSION); uint8_t length = mGetSigned(message) ? MAX_MESSAGE_LENGTH : mGetLength(message); message.last = nc.nodeId; bool ok = radio.send(to, &message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length)); From c358d8705a738f249f531d3b45fe45c058d11ee7 Mon Sep 17 00:00:00 2001 From: Marcelo Aquino Date: Thu, 19 Feb 2015 21:39:46 -0200 Subject: [PATCH 053/137] add parser class for serial and ethernet gateways --- libraries/MySensors/MyConfig.h | 5 + libraries/MySensors/MyParser.cpp | 4 + libraries/MySensors/MyParser.h | 16 +++ libraries/MySensors/MyParserSerial.cpp | 81 +++++++++++++ libraries/MySensors/MyParserSerial.h | 15 +++ libraries/MySensors/MySensor.h | 1 + .../examples/EthernetGateway/GatewayUtil.h | 110 ++++-------------- .../examples/SerialGateway/GatewayUtil.h | 110 ++++-------------- 8 files changed, 162 insertions(+), 180 deletions(-) create mode 100644 libraries/MySensors/MyParser.cpp create mode 100644 libraries/MySensors/MyParser.h create mode 100644 libraries/MySensors/MyParserSerial.cpp create mode 100644 libraries/MySensors/MyParserSerial.h diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index ecae372..deb31c1 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -35,6 +35,11 @@ typedef class MyRFDriverNRF24 MyRFDriverClass; typedef class MyRFDriverRF69 MyRFDriverClass; #endif +#if defined(MYSENSORS_SERIAL_GATEWAY) || defined(MYSENSORS_ETHERNET_GATEWAY) +#include "MyParserSerial.h" +typedef class MyParserSerial MyParserClass; +#endif + #ifdef MYSENSORS_SIGNING_DUMMY #include "MySigningDriverDummy.h" #define SIGNING_IDENTIFIER (0) // Reserved for dummy implementation, will not work with other backends diff --git a/libraries/MySensors/MyParser.cpp b/libraries/MySensors/MyParser.cpp new file mode 100644 index 0000000..dacd32b --- /dev/null +++ b/libraries/MySensors/MyParser.cpp @@ -0,0 +1,4 @@ +#include "MyParser.h" + +MyParser::MyParser() { +} diff --git a/libraries/MySensors/MyParser.h b/libraries/MySensors/MyParser.h new file mode 100644 index 0000000..e606a0d --- /dev/null +++ b/libraries/MySensors/MyParser.h @@ -0,0 +1,16 @@ +#ifndef MyParser_h +#define MyParser_h + +#include "MyMessage.h" + +class MyParser +{ +public: + // MyParser constructor + MyParser(); + // parse(message, inputString) + // parse a string into a message element + // returns true if successfully parsed the input string + virtual bool parse(MyMessage &message, char *inputString) = 0; +}; +#endif \ No newline at end of file diff --git a/libraries/MySensors/MyParserSerial.cpp b/libraries/MySensors/MyParserSerial.cpp new file mode 100644 index 0000000..dc233c0 --- /dev/null +++ b/libraries/MySensors/MyParserSerial.cpp @@ -0,0 +1,81 @@ +#include "MyParser.h" +#include "MyParserSerial.h" + +MyParserSerial::MyParserSerial() : MyParser() {} + +bool MyParserSerial::parse(MyMessage &message, char *inputString) { + char *str, *p, *value=NULL; + uint8_t bvalue[MAX_PAYLOAD]; + uint8_t blen = 0; + int i = 0; + uint8_t command = 0; + uint8_t ack = 0; + + // Extract command data coming on serial line + for (str = strtok_r(inputString, ";", &p); // split using semicolon + str && i < 6; // loop while str is not null an max 5 times + str = strtok_r(NULL, ";", &p) // get subsequent tokens + ) { + switch (i) { + case 0: // Radioid (destination) + message.destination = atoi(str); + break; + case 1: // Childid + message.sensor = atoi(str); + break; + case 2: // Message type + command = atoi(str); + mSetCommand(message, command); + break; + case 3: // Should we request ack from destination? + ack = atoi(str); + break; + case 4: // Data type + message.type = atoi(str); + break; + case 5: // Variable value + if (command == C_STREAM) { + blen = 0; + uint8_t val; + while (*str) { + val = h2i(*str++) << 4; + val += h2i(*str++); + bvalue[blen] = val; + blen++; + } + } else { + value = str; + // Remove ending carriage return character (if it exists) + uint8_t lastCharacter = strlen(value)-1; + if (value[lastCharacter] == '\r') + value[lastCharacter] = 0; + } + break; + } + i++; + } + // Check for invalid input + if (i < 5) + return false; + + message.sender = GATEWAY_ADDRESS; + message.last = GATEWAY_ADDRESS; + mSetRequestAck(message, ack?1:0); + mSetAck(message, false); + if (command == C_STREAM) + message.set(bvalue, blen); + else + message.set(value); + return true; +} + +uint8_t MyParserSerial::h2i(char c) { + uint8_t i = 0; + if (c <= '9') + i += c - '0'; + else if (c >= 'a') + i += c - 'a' + 10; + else + i += c - 'A' + 10; + return i; +} diff --git a/libraries/MySensors/MyParserSerial.h b/libraries/MySensors/MyParserSerial.h new file mode 100644 index 0000000..e7baf9b --- /dev/null +++ b/libraries/MySensors/MyParserSerial.h @@ -0,0 +1,15 @@ +#ifndef MyParserSerial_h +#define MyParserSerial_h + +#include "MyConfig.h" +#include "MyParser.h" + +class MyParserSerial : public MyParser +{ +public: + MyParserSerial(); + bool parse(MyMessage &message, char *inputString); +private: + uint8_t h2i(char c); +}; +#endif \ No newline at end of file diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 7c6405e..cdac00c 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -14,6 +14,7 @@ #include "Version.h" // Auto generated by bot #include "MyRFDriver.h" +#include "MyParser.h" #include "MySigningDriver.h" #include "MyConfig.h" #include "MyMessage.h" diff --git a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h index b5ac2ba..109f330 100644 --- a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h @@ -23,7 +23,7 @@ volatile uint8_t countErr; boolean inclusionMode; // Keeps track on inclusion mode void (*serial)(const char *fmt, ... ); -MyMessage msg; +MyParserClass parser; void setInclusionMode(boolean newMode); void txBlink(uint8_t cnt); @@ -104,102 +104,32 @@ void checkInclusionFinished() { } } -uint8_t h2i(char c) { - uint8_t i = 0; - if (c <= '9') - i += c - '0'; - else if (c >= 'a') - i += c - 'a' + 10; - else - i += c - 'A' + 10; - return i; -} - void parseAndSend(MySensor gw, char *commandBuffer) { - boolean ok = false; - char *str, *p, *value=NULL; - uint8_t bvalue[MAX_PAYLOAD]; - uint8_t blen = 0; - int i = 0; - uint16_t destination = 0; - uint8_t sensor = 0; - uint8_t command = 0; - uint8_t type = 0; - uint8_t ack = 0; + boolean ok; + MyMessage &msg = gw.getLastMessage(); - // Extract command data coming on serial line - for (str = strtok_r(commandBuffer, ";", &p); // split using semicolon - str && i < 6; // loop while str is not null an max 5 times - str = strtok_r(NULL, ";", &p) // get subsequent tokens - ) { - switch (i) { - case 0: // Radioid (destination) - destination = atoi(str); - break; - case 1: // Childid - sensor = atoi(str); - break; - case 2: // Message type - command = atoi(str); - break; - case 3: // Should we request ack from destination? - ack = atoi(str); - break; - case 4: // Data type - type = atoi(str); - break; - case 5: // Variable value - if (command == C_STREAM) { - blen = 0; - uint8_t val; - while (*str) { - val = h2i(*str++) << 4; - val += h2i(*str++); - bvalue[blen] = val; - blen++; - } - } else { - value = str; - // Remove ending carriage return character (if it exists) - uint8_t lastCharacter = strlen(value)-1; - if (value[lastCharacter] == '\r') - value[lastCharacter] = 0; - } - break; - } - i++; - } + if (parser.parse(msg, commandBuffer)) { + uint8_t command = mGetCommand(msg); - if (destination==GATEWAY_ADDRESS && command==C_INTERNAL) { - // Handle messages directed to gateway - if (type == I_VERSION) { - // Request for version - serial(PSTR("0;0;%d;0;%d;%s\n"), C_INTERNAL, I_VERSION, LIBRARY_VERSION); - } else if (type == I_INCLUSION_MODE) { - // Request to change inclusion mode - setInclusionMode(atoi(value) == 1); - } - } else { - txBlink(1); - msg.sender = GATEWAY_ADDRESS; - msg.destination = destination; - msg.sensor = sensor; - msg.type = type; - mSetCommand(msg,command); - mSetRequestAck(msg,ack?1:0); - mSetAck(msg,false); - if (command == C_STREAM) - msg.set(bvalue, blen); - else - msg.set(value); - ok = gw.sendRoute(msg); - if (!ok) { - errBlink(1); + if (msg.destination==GATEWAY_ADDRESS && command==C_INTERNAL) { + // Handle messages directed to gateway + if (msg.type == I_VERSION) { + // Request for version + serial(PSTR("0;0;%d;0;%d;%s\n"), C_INTERNAL, I_VERSION, LIBRARY_VERSION); + } else if (msg.type == I_INCLUSION_MODE) { + // Request to change inclusion mode + setInclusionMode(atoi(msg.data) == 1); + } + } else { + txBlink(1); + ok = gw.sendRoute(msg); + if (!ok) { + errBlink(1); + } } } } - void setInclusionMode(boolean newMode) { if (newMode != inclusionMode) inclusionMode = newMode; diff --git a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h index b5ac2ba..109f330 100644 --- a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h @@ -23,7 +23,7 @@ volatile uint8_t countErr; boolean inclusionMode; // Keeps track on inclusion mode void (*serial)(const char *fmt, ... ); -MyMessage msg; +MyParserClass parser; void setInclusionMode(boolean newMode); void txBlink(uint8_t cnt); @@ -104,102 +104,32 @@ void checkInclusionFinished() { } } -uint8_t h2i(char c) { - uint8_t i = 0; - if (c <= '9') - i += c - '0'; - else if (c >= 'a') - i += c - 'a' + 10; - else - i += c - 'A' + 10; - return i; -} - void parseAndSend(MySensor gw, char *commandBuffer) { - boolean ok = false; - char *str, *p, *value=NULL; - uint8_t bvalue[MAX_PAYLOAD]; - uint8_t blen = 0; - int i = 0; - uint16_t destination = 0; - uint8_t sensor = 0; - uint8_t command = 0; - uint8_t type = 0; - uint8_t ack = 0; + boolean ok; + MyMessage &msg = gw.getLastMessage(); - // Extract command data coming on serial line - for (str = strtok_r(commandBuffer, ";", &p); // split using semicolon - str && i < 6; // loop while str is not null an max 5 times - str = strtok_r(NULL, ";", &p) // get subsequent tokens - ) { - switch (i) { - case 0: // Radioid (destination) - destination = atoi(str); - break; - case 1: // Childid - sensor = atoi(str); - break; - case 2: // Message type - command = atoi(str); - break; - case 3: // Should we request ack from destination? - ack = atoi(str); - break; - case 4: // Data type - type = atoi(str); - break; - case 5: // Variable value - if (command == C_STREAM) { - blen = 0; - uint8_t val; - while (*str) { - val = h2i(*str++) << 4; - val += h2i(*str++); - bvalue[blen] = val; - blen++; - } - } else { - value = str; - // Remove ending carriage return character (if it exists) - uint8_t lastCharacter = strlen(value)-1; - if (value[lastCharacter] == '\r') - value[lastCharacter] = 0; - } - break; - } - i++; - } + if (parser.parse(msg, commandBuffer)) { + uint8_t command = mGetCommand(msg); - if (destination==GATEWAY_ADDRESS && command==C_INTERNAL) { - // Handle messages directed to gateway - if (type == I_VERSION) { - // Request for version - serial(PSTR("0;0;%d;0;%d;%s\n"), C_INTERNAL, I_VERSION, LIBRARY_VERSION); - } else if (type == I_INCLUSION_MODE) { - // Request to change inclusion mode - setInclusionMode(atoi(value) == 1); - } - } else { - txBlink(1); - msg.sender = GATEWAY_ADDRESS; - msg.destination = destination; - msg.sensor = sensor; - msg.type = type; - mSetCommand(msg,command); - mSetRequestAck(msg,ack?1:0); - mSetAck(msg,false); - if (command == C_STREAM) - msg.set(bvalue, blen); - else - msg.set(value); - ok = gw.sendRoute(msg); - if (!ok) { - errBlink(1); + if (msg.destination==GATEWAY_ADDRESS && command==C_INTERNAL) { + // Handle messages directed to gateway + if (msg.type == I_VERSION) { + // Request for version + serial(PSTR("0;0;%d;0;%d;%s\n"), C_INTERNAL, I_VERSION, LIBRARY_VERSION); + } else if (msg.type == I_INCLUSION_MODE) { + // Request to change inclusion mode + setInclusionMode(atoi(msg.data) == 1); + } + } else { + txBlink(1); + ok = gw.sendRoute(msg); + if (!ok) { + errBlink(1); + } } } } - void setInclusionMode(boolean newMode) { if (newMode != inclusionMode) inclusionMode = newMode; From 2d8fddcb051dda404b0c133e364f9dc658662646 Mon Sep 17 00:00:00 2001 From: Marcelo Aquino Date: Sat, 21 Feb 2015 23:41:00 -0200 Subject: [PATCH 054/137] check valid parentNodeId before requestNodeId --- libraries/MySensors/MySensor.cpp | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 149f3d8..c104c24 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -87,22 +87,19 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b findParentNode(); } - if ( (_nodeId != AUTO) && (nc.nodeId != _nodeId) ) { - // Set static id - nc.nodeId = _nodeId; - // Save static id in eeprom - eeprom_update_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, _nodeId); - } - - // Try to fetch node-id from gateway - if (nc.nodeId == AUTO) { + if (_nodeId != AUTO) { + // Set static id + nc.nodeId = _nodeId; + // Save static id in eeprom + eeprom_update_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, _nodeId); + } else if (isValidParent(nc.parentNodeId)) { + // Try to fetch node-id from gateway requestNodeId(); } setupNode(); debug(PSTR("%s started, id=%d, parent=%d, distance=%d\n"), isGateway?"gateway":(repeaterMode?"repeater":"sensor"), nc.nodeId, nc.parentNodeId, nc.distance); - } void MySensor::setupRepeaterMode(){ From fb1c542862221f0678485a553b46120bf09c6a91 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Sun, 22 Feb 2015 23:22:06 +0100 Subject: [PATCH 055/137] Move SHA204 personalizer sketch to MySensors examples Fix include errors. --- .../examples/Sha204Personalizer/Sha204Personalizer.ino} | 0 .../sha204/{sha204_includes => }/sha204_lib_return_codes.h | 0 libraries/sha204/sha204_library.cpp | 4 ++-- 3 files changed, 2 insertions(+), 2 deletions(-) rename libraries/{sha204/examples/sha204_personalizer/sha204_personalizer.ino => MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino} (100%) rename libraries/sha204/{sha204_includes => }/sha204_lib_return_codes.h (100%) diff --git a/libraries/sha204/examples/sha204_personalizer/sha204_personalizer.ino b/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino similarity index 100% rename from libraries/sha204/examples/sha204_personalizer/sha204_personalizer.ino rename to libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino diff --git a/libraries/sha204/sha204_includes/sha204_lib_return_codes.h b/libraries/sha204/sha204_lib_return_codes.h similarity index 100% rename from libraries/sha204/sha204_includes/sha204_lib_return_codes.h rename to libraries/sha204/sha204_lib_return_codes.h diff --git a/libraries/sha204/sha204_library.cpp b/libraries/sha204/sha204_library.cpp index 44e59bd..8e43890 100644 --- a/libraries/sha204/sha204_library.cpp +++ b/libraries/sha204/sha204_library.cpp @@ -1,6 +1,6 @@ #include "Arduino.h" #include "sha204_library.h" -#include "sha204_includes/sha204_lib_return_codes.h" +#include "sha204_lib_return_codes.h" // atsha204Class Constructor @@ -816,4 +816,4 @@ uint8_t atsha204Class::sha204c_check_crc(uint8_t *response) return (crc[0] == response[count] && crc[1] == response[count + 1]) ? SHA204_SUCCESS : SHA204_BAD_CRC; -} \ No newline at end of file +} From 2ab9822172aae1a06be8d115f60daf8347a801b1 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sun, 22 Feb 2015 23:31:18 +0100 Subject: [PATCH 056/137] Bugfix for gateway signing requirements Gateway now only indicate signing requirements for sensors that in turn have indicated signing requirements. --- libraries/MySensors/MySensor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 149f3d8..4c7e837 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -402,8 +402,8 @@ boolean MySensor::process() { // We do not currently want a gateway to require signing from all nodes in a network just because it wants one node // to sign it's messages if (isGateway) { - if (requireSigning) - sendRoute(build(msg, nc.nodeId, msg.sender, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(requireSigning)); + if (requireSigning && DO_SIGN(msg.sender)) + sendRoute(build(msg, nc.nodeId, msg.sender, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(true)); else sendRoute(build(msg, nc.nodeId, msg.sender, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(false)); } From 961366313bcd1911d72d462e179ea0df2e7c1cd9 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Wed, 25 Feb 2015 22:24:44 +0100 Subject: [PATCH 057/137] Fixed bug that caused the wrong message to be signed process() altered the message buffer pending signing when called in sign() causing the wrong message to be sent to the signing backend. This is resolved by copying the original message before processing incoming messages to make sure the original message is kept. After it is successfully signed, it is copied back to its original location again. Also, the old 'ack' message buffer is renamed to tmpMsg to indicate its use as a temporary message buffer for various purposes. --- libraries/MySensors/MySensor.cpp | 23 +++++++++++++---------- libraries/MySensors/MySensor.h | 3 ++- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 3012a5d..ce971f7 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -349,12 +349,12 @@ boolean MySensor::process() { // Check if sender requests an ack back. if (mGetRequestAck(msg)) { // Copy message - ack = msg; - mSetRequestAck(ack,false); // Reply without ack flag (otherwise we would end up in an eternal loop) - mSetAck(ack,true); - ack.sender = nc.nodeId; - ack.destination = msg.sender; - sendRoute(ack); + tmpMsg = msg; + mSetRequestAck(tmpMsg,false); // Reply without ack flag (otherwise we would end up in an eternal loop) + mSetAck(tmpMsg,true); + tmpMsg.sender = nc.nodeId; + tmpMsg.destination = msg.sender; + sendRoute(tmpMsg); } if (command == C_INTERNAL) { @@ -591,18 +591,21 @@ int8_t MySensor::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, ui } bool MySensor::sign(MyMessage &message) { - MyMessage msgNonce; - if (!sendRoute(build(msgNonce, nc.nodeId, message.destination, message.sensor, C_INTERNAL, I_GET_NONCE, false).set(""))) { + if (!sendRoute(build(tmpMsg, nc.nodeId, message.destination, message.sensor, C_INTERNAL, I_GET_NONCE, false).set(""))) { return false; } else { // We have to wait for the nonce to arrive before we can sign our original message // Other messages could come in-between. We trust process() takes care of them unsigned long enter = millis(); + msgSign = message; // Copy the message to sign since message buffer might be touched in process() while (millis() - enter < 5000) { if (process()) { - if (getLastMessage().type == I_GET_NONCE_RESPONSE) { + if (mGetCommand(getLastMessage()) == C_INTERNAL && getLastMessage().type == I_GET_NONCE_RESPONSE) { // Proceed with signing if nonce has been received - if (signer.putNonce(getLastMessage()) && signer.signMsg(message)) return true; + if (signer.putNonce(getLastMessage()) && signer.signMsg(msgSign)) { + message = msgSign; // Write the signed message back + return true; + } break; } } diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index cdac00c..747990a 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -246,7 +246,8 @@ class MySensor uint16_t doSign[16]; // Bitfield indicating which sensors require signed communication MyMessage msg; // Buffer for incoming messages. - MyMessage ack; // Buffer for ack messages. + MyMessage tmpMsg ; // Buffer for temporary messages (acks and nonces among others). + MyMessage msgSign; // Buffer for message to sign. MyRFDriverClass radio; From 23a8a48f8e48630a4cf4aae5a46fe7f622c85df3 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 25 Feb 2015 23:18:26 +0100 Subject: [PATCH 058/137] Rename "Dummy" signing driver to "None" --- libraries/MySensors/MyConfig.h | 8 ++--- ...riverDummy.cpp => MySigningDriverNone.cpp} | 34 +++++++++---------- ...ingDriverDummy.h => MySigningDriverNone.h} | 14 ++++---- 3 files changed, 28 insertions(+), 28 deletions(-) rename libraries/MySensors/{MySigningDriverDummy.cpp => MySigningDriverNone.cpp} (52%) rename libraries/MySensors/{MySigningDriverDummy.h => MySigningDriverNone.h} (63%) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index deb31c1..c574b58 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -16,7 +16,7 @@ //#define MYSENSORS_RF_RF69 // Choose signing backend by enabling one of the following -#define MYSENSORS_SIGNING_DUMMY +#define MYSENSORS_SIGNING_NONE //#define MYSENSORS_SIGNING_ATSHA204 //#define MYSENSORS_SIGNING_ATSHA204SOFT @@ -40,10 +40,10 @@ typedef class MyRFDriverRF69 MyRFDriverClass; typedef class MyParserSerial MyParserClass; #endif -#ifdef MYSENSORS_SIGNING_DUMMY -#include "MySigningDriverDummy.h" +#ifdef MYSENSORS_SIGNING_NONE +#include "MySigningDriverNone.h" #define SIGNING_IDENTIFIER (0) // Reserved for dummy implementation, will not work with other backends -typedef class MySigningDriverDummy MySigningDriverClass; +typedef class MySigningDriverNone MySigningDriverClass; #endif #ifdef MYSENSORS_SIGNING_ATSHA204 diff --git a/libraries/MySensors/MySigningDriverDummy.cpp b/libraries/MySensors/MySigningDriverNone.cpp similarity index 52% rename from libraries/MySensors/MySigningDriverDummy.cpp rename to libraries/MySensors/MySigningDriverNone.cpp index f5bac3f..fed6e6c 100644 --- a/libraries/MySensors/MySigningDriverDummy.cpp +++ b/libraries/MySensors/MySigningDriverNone.cpp @@ -1,23 +1,23 @@ /* - Dummy signing backend. Does not provide any security measures. + Disabled signing backend. Does not provide any security measures. Created by Patrick "Anticimex" Fallberg */ #include "MySigningDriver.h" -#include "MySigningDriverDummy.h" +#include "MySigningDriverNone.h" -#ifdef MYSENSORS_SIGNING_DUMMY +#ifdef MYSENSORS_SIGNING_NONE // Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) -//#define DEBUG_DUMMY_SIGNING +//#define DEBUG_NONE_SIGNING -#ifdef DEBUG_DUMMY_SIGNING -#define DEBUG_DUMMY_PRINTLN(args) Serial.println(args) +#ifdef DEBUG_NONE_SIGNING +#define DEBUG_NONE_PRINTLN(args) Serial.println(args) #else -#define DEBUG_DUMMY_PRINTLN(args) +#define DEBUG_NONE_PRINTLN(args) #endif -#ifdef DEBUG_DUMMY_SIGNING -static void DEBUG_DUMMY_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) +#ifdef DEBUG_NONE_SIGNING +static void DEBUG_NONE_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) { int i; Serial.println(str); @@ -32,28 +32,28 @@ static void DEBUG_DUMMY_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) Serial.println(); } #else -#define DEBUG_DUMMY_PRINTBUF(str, buf, sz) +#define DEBUG_NONE_PRINTBUF(str, buf, sz) #endif -MySigningDriverDummy::MySigningDriverDummy() : MySigningDriver() { +MySigningDriverNone::MySigningDriverNone() : MySigningDriver() { } -bool MySigningDriverDummy::getNonce(MyMessage &msg) { +bool MySigningDriverNone::getNonce(MyMessage &msg) { return true; } -bool MySigningDriverDummy::checkTimer() { +bool MySigningDriverNone::checkTimer() { return true; } -bool MySigningDriverDummy::putNonce(MyMessage &msg) { +bool MySigningDriverNone::putNonce(MyMessage &msg) { return true; } -bool MySigningDriverDummy::signMsg(MyMessage &msg) { +bool MySigningDriverNone::signMsg(MyMessage &msg) { // If we cannot fit any signature in the message, refuse to sign it if (mGetLength(msg) > MAX_PAYLOAD-2) { - DEBUG_DUMMY_PRINTLN("Cannot fit any signature to this message"); + DEBUG_NONE_PRINTLN("Cannot fit any signature to this message"); return false; } mSetSigned(msg, 1); // make sure signing flag is set before signature is calculated @@ -61,7 +61,7 @@ bool MySigningDriverDummy::signMsg(MyMessage &msg) { return true; } -bool MySigningDriverDummy::verifyMsg(MyMessage &msg) { +bool MySigningDriverNone::verifyMsg(MyMessage &msg) { if (msg.data[mGetLength(msg)] != SIGNING_IDENTIFIER) return false; else diff --git a/libraries/MySensors/MySigningDriverDummy.h b/libraries/MySensors/MySigningDriverNone.h similarity index 63% rename from libraries/MySensors/MySigningDriverDummy.h rename to libraries/MySensors/MySigningDriverNone.h index bf5ee81..8c30367 100644 --- a/libraries/MySensors/MySigningDriverDummy.h +++ b/libraries/MySensors/MySigningDriverNone.h @@ -1,24 +1,24 @@ /* - Dummy signing backend. Does not provide any security measures. + Disabled signing backend. Does not provide any security measures. Created by Patrick "Anticimex" Fallberg */ -#ifndef MySigningDriverDummy_h -#define MySigningDriverDummy_h +#ifndef MySigningDriverNone_h +#define MySigningDriverNone_h #include "MyConfig.h" #include "MySigningDriver.h" #include -// The dummy signing driver that can be used for nodes +// The "none" signing driver that can be used for nodes // not requiring signing // It does check SIGNING_IDENTIFIER byte to avoid illegal mixing of signing back-ends in // the network (as seen by this node) and it does verify proper execution order on the API. -// The dummy driver rejects all other back-ends. -class MySigningDriverDummy : public MySigningDriver +// The "none" driver rejects all other back-ends. +class MySigningDriverNone : public MySigningDriver { public: - MySigningDriverDummy(); + MySigningDriverNone(); bool getNonce(MyMessage &msg); bool checkTimer(void); bool putNonce(MyMessage &msg); From bf8102ecadd53772e7887c75248c61194e9dd182 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 26 Feb 2015 23:53:37 +0100 Subject: [PATCH 059/137] For discussion --- libraries/MySensors/MyConfig.h | 103 ++++-------------- libraries/MySensors/MyParserSerial.cpp | 1 + libraries/MySensors/MyRFDriverNRF24.cpp | 58 +++++----- libraries/MySensors/MyRFDriverNRF24.h | 25 +---- libraries/MySensors/MySensor.cpp | 6 +- libraries/MySensors/MySensor.h | 7 +- .../MySensors/MySigningDriverAtsha204.cpp | 16 +-- libraries/MySensors/MySigningDriverAtsha204.h | 3 + .../MySensors/MySigningDriverAtsha204Soft.cpp | 14 +-- .../MySensors/MySigningDriverAtsha204Soft.h | 3 + libraries/MySensors/MySigningDriverNone.cpp | 2 - libraries/MySensors/MySigningDriverNone.h | 2 + .../examples/RelayActuator/RelayActuator.ino | 6 +- 13 files changed, 90 insertions(+), 156 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index c574b58..168a5fc 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -1,99 +1,36 @@ #ifndef MyConfig_h #define MyConfig_h -/*** - * Configure Sensor Network - */ - -// pick ONE of these - other board layouts can be easily added this way -#define MYSENSORS_SENSOR -//#define MYSENSORS_SERIAL_GATEWAY -//#define MYSENSORS_ETHERNET_GATEWAY -//#define MYSENSORS_MQTT_GATEWAY +/********************************** +* Enable/Disable debug logging +***********************************/ +#define DEBUG -// Choose radio type by enabling one of the following -#define MYSENSORS_RF_NRF24 -//#define MYSENSORS_RF_RF69 - -// Choose signing backend by enabling one of the following -#define MYSENSORS_SIGNING_NONE -//#define MYSENSORS_SIGNING_ATSHA204 -//#define MYSENSORS_SIGNING_ATSHA204SOFT +/********************************** +* Message Signing Settings +***********************************/ // Define a suitable timeout for a signature verification session // Consider the turnaround from a nonce being generated to a signed message being received // which might vary, especially in networks with many hops. 5s ought to be enough for anyone. -#define VERIFICATION_TIMEOUT_MS 5000 +#define MY_VERIFICATION_TIMEOUT_MS 5000 -#ifdef MYSENSORS_RF_NRF24 -#include "MyRFDriverNRF24.h" -typedef class MyRFDriverNRF24 MyRFDriverClass; -#endif +// MySigningDriverAtsha204 settinga +#define MY_ATSHA204_PIN 17 // A3 - pin where ATSHA204 is attached -#ifdef MYSENSORS_RF_RF69 -#include "MyRFDriverRF69.h" -typedef class MyRFDriverRF69 MyRFDriverClass; -#endif +// MySigningDriverAtsha204Soft settings +#define MY_RANDOMSEED_PIN 7 // A7 - Pin used for random generation (do not connect anything to this) +// Key to use for HMAC calculation in MySigningDriverAtsha204Soft (32 bytes) +#define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 -#if defined(MYSENSORS_SERIAL_GATEWAY) || defined(MYSENSORS_ETHERNET_GATEWAY) -#include "MyParserSerial.h" -typedef class MyParserSerial MyParserClass; -#endif -#ifdef MYSENSORS_SIGNING_NONE -#include "MySigningDriverNone.h" -#define SIGNING_IDENTIFIER (0) // Reserved for dummy implementation, will not work with other backends -typedef class MySigningDriverNone MySigningDriverClass; -#endif +/********************************** +* NRF24L01 Driver Defaults +***********************************/ +#define RF24_CE_PIN 9 +#define RF24_CS_PIN 10 +#define RF24_PA_LEVEL RF24_PA_MAX -#ifdef MYSENSORS_SIGNING_ATSHA204 -#ifdef MYSENSORS_SENSOR -#define ATSHA204_PIN 17 //A3 -#endif -#ifdef MYSENSORS_SERIAL_GATEWAY -#define ATSHA204_PIN 17 //A3 -#endif - -#if defined(MYSENSORS_ETHERNET_GATEWAY) || defined(MYSENSORS_MQTT_GATEWAY) -#define ATSHA204_PIN 17 //A3 -#endif - -#include "MySigningDriverAtsha204.h" -#define SIGNING_IDENTIFIER (1) // SHA256-based HMAC (ATSHA204 specific) -typedef class MySigningDriverAtsha204 MySigningDriverClass; -#endif - -#ifdef MYSENSORS_SIGNING_ATSHA204SOFT -// Key to use for HMAC calculation -static uint8_t hmacKey[32] = { -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 -}; - -// Pick an unconnected analog pin for RANDOMSEED_PIN -#ifdef MYSENSORS_SENSOR -#define RANDOMSEED_PIN 7 //A7 -#endif - -#ifdef MYSENSORS_SERIAL_GATEWAY -#define RANDOMSEED_PIN 7 //A7 -#endif - -#if defined(MYSENSORS_ETHERNET_GATEWAY) || defined(MYSENSORS_MQTT_GATEWAY) -#define RANDOMSEED_PIN 7 //A7 -#endif - -#include "MySigningDriverAtsha204Soft.h" -#define SIGNING_IDENTIFIER (1) // SHA256-based HMAC (ATSHA204 specific) -typedef class MySigningDriverAtsha204Soft MySigningDriverClass; -#endif - -/*** - * Enable/Disable debug logging - */ -#define DEBUG #endif diff --git a/libraries/MySensors/MyParserSerial.cpp b/libraries/MySensors/MyParserSerial.cpp index dc233c0..8c020b5 100644 --- a/libraries/MySensors/MyParserSerial.cpp +++ b/libraries/MySensors/MyParserSerial.cpp @@ -1,5 +1,6 @@ #include "MyParser.h" #include "MyParserSerial.h" +#include "MyRFDriver.h" MyParserSerial::MyParserSerial() : MyParser() {} diff --git a/libraries/MySensors/MyRFDriverNRF24.cpp b/libraries/MySensors/MyRFDriverNRF24.cpp index 1667fc6..9b4fe45 100644 --- a/libraries/MySensors/MyRFDriverNRF24.cpp +++ b/libraries/MySensors/MyRFDriverNRF24.cpp @@ -1,37 +1,41 @@ #include "MyRFDriver.h" #include "MyRFDriverNRF24.h" -MyRFDriverNRF24::MyRFDriverNRF24() : MyRFDriver() { - rf24 = new RF24(RF24_CE_PIN, RF24_CS_PIN); +MyRFDriverNRF24::MyRFDriverNRF24(uint8_t ce, uint8_t cs, uint8_t paLevel) + : + MyRFDriver(), + rf24(ce, cs), + _paLevel(paLevel) +{ } void MyRFDriverNRF24::init() { // Start up the radio library - rf24->begin(); + rf24.begin(); - if (!rf24->isPVariant()) { + if (!rf24.isPVariant()) { debug(PSTR("check wires\n")); while(1); } - rf24->setAutoAck(1); - rf24->setAutoAck(BROADCAST_PIPE,false); // Turn off auto ack for broadcast - rf24->enableAckPayload(); - rf24->setChannel(RF24_CHANNEL); - rf24->setPALevel(RF24_PA_LEVEL); - rf24->setDataRate(RF24_DATARATE); - rf24->setRetries(5,15); - rf24->setCRCLength(RF24_CRC_16); - rf24->enableDynamicPayloads(); + rf24.setAutoAck(1); + rf24.setAutoAck(BROADCAST_PIPE,false); // Turn off auto ack for broadcast + rf24.enableAckPayload(); + rf24.setChannel(RF24_CHANNEL); + rf24.setPALevel(_paLevel); + rf24.setDataRate(RF24_DATARATE); + rf24.setRetries(5,15); + rf24.setCRCLength(RF24_CRC_16); + rf24.enableDynamicPayloads(); // All nodes listen to broadcast pipe (for FIND_PARENT_RESPONSE messages) - rf24->openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); + rf24.openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); } void MyRFDriverNRF24::setAddress(uint8_t address) { _address = address; - rf24->openReadingPipe(WRITE_PIPE, TO_ADDR(address)); - rf24->openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(address)); - rf24->startListening(); + rf24.openReadingPipe(WRITE_PIPE, TO_ADDR(address)); + rf24.openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(address)); + rf24.startListening(); } uint8_t MyRFDriverNRF24::getAddress() { @@ -40,30 +44,30 @@ uint8_t MyRFDriverNRF24::getAddress() { bool MyRFDriverNRF24::send(uint8_t to, const void* data, uint8_t len) { // Make sure radio has powered up - rf24->powerUp(); - rf24->stopListening(); - rf24->openWritingPipe(TO_ADDR(to)); - bool ok = rf24->write(data, len, to == BROADCAST_ADDRESS); - rf24->startListening(); + rf24.powerUp(); + rf24.stopListening(); + rf24.openWritingPipe(TO_ADDR(to)); + bool ok = rf24.write(data, len, to == BROADCAST_ADDRESS); + rf24.startListening(); return ok; } bool MyRFDriverNRF24::available(uint8_t *to) { uint8_t pipe = 255; - boolean avail = rf24->available(&pipe); + boolean avail = rf24.available(&pipe); if (pipe == CURRENT_NODE_PIPE) *to = _address; else if (pipe == BROADCAST_PIPE) *to = BROADCAST_ADDRESS; - return (rf24->available() && pipe < 6); + return (rf24.available() && pipe < 6); } uint8_t MyRFDriverNRF24::receive(void* data) { - uint8_t len = rf24->getDynamicPayloadSize(); - rf24->read(data, len); + uint8_t len = rf24.getDynamicPayloadSize(); + rf24.read(data, len); return len; } void MyRFDriverNRF24::powerDown() { - rf24->powerDown(); + rf24.powerDown(); } diff --git a/libraries/MySensors/MyRFDriverNRF24.h b/libraries/MySensors/MyRFDriverNRF24.h index 267b19c..21607e2 100644 --- a/libraries/MySensors/MyRFDriverNRF24.h +++ b/libraries/MySensors/MyRFDriverNRF24.h @@ -7,26 +7,6 @@ #include "utility/RF24.h" #include "utility/RF24_config.h" - - -#ifdef MYSENSORS_SENSOR -#define RF24_CE_PIN 9 -#define RF24_CS_PIN 10 -#define RF24_PA_LEVEL RF24_PA_MAX -#endif - -#ifdef MYSENSORS_SERIAL_GATEWAY -#define RF24_CE_PIN 9 -#define RF24_CS_PIN 10 -#define RF24_PA_LEVEL RF24_PA_LOW -#endif - -#if defined(MYSENSORS_ETHERNET_GATEWAY) || defined(MYSENSORS_MQTT_GATEWAY) -#define RF24_CE_PIN 5 -#define RF24_CS_PIN 6 -#define RF24_PA_LEVEL RF24_PA_LOW -#endif - #define RF24_CHANNEL 76 //RF channel for the sensor net, 0-127 #define RF24_DATARATE RF24_250KBPS //RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps #define RF24_BASE_RADIO_ID ((uint64_t)0xA8A8E1FC00LL) // This is also act as base value for sensor nodeId addresses. Change this (or channel) if you have more than one sensor network. @@ -40,7 +20,7 @@ class MyRFDriverNRF24 : public MyRFDriver { public: - MyRFDriverNRF24(); + MyRFDriverNRF24(uint8_t ce=RF24_CE_PIN, uint8_t cs=RF24_CS_PIN, uint8_t paLevel=RF24_PA_LEVEL); void init(); void setAddress(uint8_t address); uint8_t getAddress(); @@ -49,8 +29,9 @@ public: uint8_t receive(void* data); void powerDown(); private: - RF24 *rf24; + RF24 rf24; uint8_t _address; + uint8_t _paLevel; }; #endif diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index ce971f7..aab91ec 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -37,7 +37,11 @@ static inline bool isValidDistance( const uint8_t distance ) { return distance != DISTANCE_INVALID; } -MySensor::MySensor() { +MySensor::MySensor(MyRFDriver &_radio, MySigningDriver &_signer) + : + radio(_radio), + signer(_signer) +{ } diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 747990a..01ca2b4 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -79,7 +79,7 @@ class MySensor * Creates a new instance of Sensor class. * */ - MySensor(); + MySensor(MyRFDriver &radio, MySigningDriver &signer); /** * Begin operation of the MySensors library @@ -249,9 +249,8 @@ class MySensor MyMessage tmpMsg ; // Buffer for temporary messages (acks and nonces among others). MyMessage msgSign; // Buffer for message to sign. - MyRFDriverClass radio; - - MySigningDriverClass signer; + MyRFDriver& radio; + MySigningDriver& signer; void setupRepeaterMode(); boolean sendWrite(uint8_t dest, MyMessage &message); diff --git a/libraries/MySensors/MySigningDriverAtsha204.cpp b/libraries/MySensors/MySigningDriverAtsha204.cpp index a71a30a..fab6942 100644 --- a/libraries/MySensors/MySigningDriverAtsha204.cpp +++ b/libraries/MySensors/MySigningDriverAtsha204.cpp @@ -7,7 +7,6 @@ #include "MySigningDriver.h" #include "MySigningDriverAtsha204.h" -#ifdef MYSENSORS_SIGNING_ATSHA204 // Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) //#define DEBUG_ATSHA_SIGNING @@ -36,11 +35,13 @@ static void DEBUG_ATSHA_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) #define DEBUG_ATSHA_PRINTBUF(str, buf, sz) #endif -static atsha204Class atsha204(ATSHA204_PIN); - -MySigningDriverAtsha204::MySigningDriverAtsha204() : MySigningDriver() { - verification_ongoing = false; +MySigningDriverAtsha204::MySigningDriverAtsha204() + : + MySigningDriver(), + atsha204(MY_ATSHA204_PIN), + verification_ongoing(false) +{ // We set the part of the 32-byte nonce that does not fit into a message to 0xAA memset(current_nonce, 0xAA, sizeof(current_nonce)); } @@ -73,13 +74,13 @@ bool MySigningDriverAtsha204::getNonce(MyMessage &msg) { // Be a little fancy to handle turnover (prolong the time allowed to timeout after turnover) // Note that if message is "too" quick, and arrives before turnover, it will be rejected // but this is consider such a rare case that it is accepted and rejects are 'safe' - if (timestamp + VERIFICATION_TIMEOUT_MS < millis()) timestamp = 0; + if (timestamp + MY_VERIFICATION_TIMEOUT_MS < millis()) timestamp = 0; return true; } bool MySigningDriverAtsha204::checkTimer() { if (verification_ongoing) { - if (millis() < timestamp || millis() > timestamp + VERIFICATION_TIMEOUT_MS) { + if (millis() < timestamp || millis() > timestamp + MY_VERIFICATION_TIMEOUT_MS) { DEBUG_ATSHA_PRINTLN("Verification timeout"); // Purge nonce memset(current_nonce, 0xAA, NONCE_NUMIN_SIZE_PASSTHROUGH); @@ -214,4 +215,3 @@ bool MySigningDriverAtsha204::calculateSignature(MyMessage &msg) { DEBUG_ATSHA_PRINTBUF("HMAC:", &rx_buffer[SHA204_BUFFER_POS_DATA], 32); return true; // We return with the signature in rx_buffer[SHA204_BUFFER_POS_DATA] } -#endif diff --git a/libraries/MySensors/MySigningDriverAtsha204.h b/libraries/MySensors/MySigningDriverAtsha204.h index a2f6b9d..57bb2f3 100644 --- a/libraries/MySensors/MySigningDriverAtsha204.h +++ b/libraries/MySensors/MySigningDriverAtsha204.h @@ -12,6 +12,8 @@ #include "utility/ATSHA204.h" #include +#define SIGNING_IDENTIFIER (1) + // The ATSHA204 is capable of generating proper random numbers for nonce // and can calculate HMAC-SHA256 signatures. This is enterprise- // level of security and ought to implement the signing needs for anybody. @@ -25,6 +27,7 @@ public: bool signMsg(MyMessage &msg); bool verifyMsg(MyMessage &msg); private: + atsha204Class atsha204; unsigned long timestamp; bool verification_ongoing; uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH]; diff --git a/libraries/MySensors/MySigningDriverAtsha204Soft.cpp b/libraries/MySensors/MySigningDriverAtsha204Soft.cpp index aaff71f..47b57f3 100644 --- a/libraries/MySensors/MySigningDriverAtsha204Soft.cpp +++ b/libraries/MySensors/MySigningDriverAtsha204Soft.cpp @@ -7,11 +7,11 @@ Created by Patrick "Anticimex" Fallberg */ +#include "MyConfig.h" #include "MySigningDriver.h" #include "MySigningDriverAtsha204Soft.h" -#include "sha256.h" +#include "utility/sha256.h" -#ifdef MYSENSORS_SIGNING_ATSHA204SOFT // Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) //#define DEBUG_ATSHASOFT_SIGNING @@ -42,16 +42,15 @@ static void DEBUG_ATSHASOFT_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) static Sha256Class Sha256; -MySigningDriverAtsha204Soft::MySigningDriverAtsha204Soft() : MySigningDriver() { +MySigningDriverAtsha204Soft::MySigningDriverAtsha204Soft() : MySigningDriver(), hmacKey({MY_HMAC_KEY}) { verification_ongoing = false; - // We set the part of the 32-byte nonce that does not fit into a message to 0xAA memset(current_nonce, 0xAA, sizeof(current_nonce)); } bool MySigningDriverAtsha204Soft::getNonce(MyMessage &msg) { // Set randomseed - randomSeed(analogRead(RANDOMSEED_PIN)); + randomSeed(analogRead(MY_RANDOMSEED_PIN)); for (int i = 0; i < MAX_PAYLOAD; i++) { current_nonce[i] = random(255); @@ -65,13 +64,13 @@ bool MySigningDriverAtsha204Soft::getNonce(MyMessage &msg) { // Be a little fancy to handle turnover (prolong the time allowed to timeout after turnover) // Note that if message is "too" quick, and arrives before turnover, it will be rejected // but this is consider such a rare case that it is accepted and rejects are 'safe' - if (timestamp + VERIFICATION_TIMEOUT_MS < millis()) timestamp = 0; + if (timestamp + MY_VERIFICATION_TIMEOUT_MS < millis()) timestamp = 0; return true; } bool MySigningDriverAtsha204Soft::checkTimer() { if (verification_ongoing) { - if (millis() < timestamp || millis() > timestamp + VERIFICATION_TIMEOUT_MS) { + if (millis() < timestamp || millis() > timestamp + MY_VERIFICATION_TIMEOUT_MS) { DEBUG_ATSHASOFT_PRINTLN("Verification timeout"); // Purge nonce memset(current_nonce, 0xAA, 32); @@ -222,4 +221,3 @@ bool MySigningDriverAtsha204Soft::calculateSignature(MyMessage &msg) { DEBUG_ATSHASOFT_PRINTBUF("HMAC:", hmac, 32); return true; } -#endif diff --git a/libraries/MySensors/MySigningDriverAtsha204Soft.h b/libraries/MySensors/MySigningDriverAtsha204Soft.h index 16d8d3e..53d8426 100644 --- a/libraries/MySensors/MySigningDriverAtsha204Soft.h +++ b/libraries/MySensors/MySigningDriverAtsha204Soft.h @@ -15,6 +15,8 @@ #include "utility/ATSHA204.h" #include +#define SIGNING_IDENTIFIER (1) + // This implementation is the pure software variant of the ATSHA204. // It is designed to work fully compliant with nodes using ATSHA204 in the network // and therefore uses the same signing identifier as ATSHA204. @@ -36,6 +38,7 @@ private: bool verification_ongoing; uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH]; uint8_t temp_message[32]; + uint8_t hmacKey[32]; uint8_t* hmac; bool calculateSignature(MyMessage &msg); }; diff --git a/libraries/MySensors/MySigningDriverNone.cpp b/libraries/MySensors/MySigningDriverNone.cpp index fed6e6c..a7ace62 100644 --- a/libraries/MySensors/MySigningDriverNone.cpp +++ b/libraries/MySensors/MySigningDriverNone.cpp @@ -6,7 +6,6 @@ #include "MySigningDriver.h" #include "MySigningDriverNone.h" -#ifdef MYSENSORS_SIGNING_NONE // Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) //#define DEBUG_NONE_SIGNING @@ -67,4 +66,3 @@ bool MySigningDriverNone::verifyMsg(MyMessage &msg) { else return true; } -#endif diff --git a/libraries/MySensors/MySigningDriverNone.h b/libraries/MySensors/MySigningDriverNone.h index 8c30367..9718a78 100644 --- a/libraries/MySensors/MySigningDriverNone.h +++ b/libraries/MySensors/MySigningDriverNone.h @@ -10,6 +10,8 @@ #include "MySigningDriver.h" #include +#define SIGNING_IDENTIFIER (0) + // The "none" signing driver that can be used for nodes // not requiring signing // It does check SIGNING_IDENTIFIER byte to avoid illegal mixing of signing back-ends in diff --git a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino index 3f0e94f..c0e8a7c 100644 --- a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino +++ b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino @@ -1,6 +1,8 @@ // Example sketch showing how to control physical relays. // This example will remember relay state even after power failure. +#include +#include #include #include @@ -9,7 +11,9 @@ #define RELAY_ON 1 // GPIO value to write to turn on attached relay #define RELAY_OFF 0 // GPIO value to write to turn off attached relay -MySensor gw; +MyRFDriverNRF24 radio; // NRFRF24L01 radio driver +MySigningDriverNone signer; // Message signing disabled +MySensor gw(radio, signer); void setup() { From ee6e34b59a4330348eb5777db195faed8f4a800d Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Fri, 27 Feb 2015 00:25:08 +0100 Subject: [PATCH 060/137] Remove global initialization of sha256 --- libraries/MySensors/MySigningDriverAtsha204Soft.cpp | 10 +++++++--- libraries/MySensors/MySigningDriverAtsha204Soft.h | 2 ++ libraries/MySensors/utility/sha256.cpp | 1 + 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/libraries/MySensors/MySigningDriverAtsha204Soft.cpp b/libraries/MySensors/MySigningDriverAtsha204Soft.cpp index 47b57f3..b57ab11 100644 --- a/libraries/MySensors/MySigningDriverAtsha204Soft.cpp +++ b/libraries/MySensors/MySigningDriverAtsha204Soft.cpp @@ -40,10 +40,14 @@ static void DEBUG_ATSHASOFT_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) #define DEBUG_ATSHASOFT_PRINTBUF(str, buf, sz) #endif -static Sha256Class Sha256; +MySigningDriverAtsha204Soft::MySigningDriverAtsha204Soft() + : + MySigningDriver(), + hmacKey({MY_HMAC_KEY}), + verification_ongoing(false), + Sha256() -MySigningDriverAtsha204Soft::MySigningDriverAtsha204Soft() : MySigningDriver(), hmacKey({MY_HMAC_KEY}) { - verification_ongoing = false; +{ // We set the part of the 32-byte nonce that does not fit into a message to 0xAA memset(current_nonce, 0xAA, sizeof(current_nonce)); } diff --git a/libraries/MySensors/MySigningDriverAtsha204Soft.h b/libraries/MySensors/MySigningDriverAtsha204Soft.h index 53d8426..014589a 100644 --- a/libraries/MySensors/MySigningDriverAtsha204Soft.h +++ b/libraries/MySensors/MySigningDriverAtsha204Soft.h @@ -13,6 +13,7 @@ #include "MyConfig.h" #include "MySigningDriver.h" #include "utility/ATSHA204.h" +#include "utility/sha256.h" #include #define SIGNING_IDENTIFIER (1) @@ -34,6 +35,7 @@ public: bool signMsg(MyMessage &msg); bool verifyMsg(MyMessage &msg); private: + Sha256Class Sha256; unsigned long timestamp; bool verification_ongoing; uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH]; diff --git a/libraries/MySensors/utility/sha256.cpp b/libraries/MySensors/utility/sha256.cpp index f492690..f0376ab 100644 --- a/libraries/MySensors/utility/sha256.cpp +++ b/libraries/MySensors/utility/sha256.cpp @@ -3,6 +3,7 @@ #include #include "sha256.h" + const uint32_t sha256K[] PROGMEM = { 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, From afce932cffbf2f86714f2ec0d12a2641df50fc98 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Fri, 27 Feb 2015 22:17:05 +0100 Subject: [PATCH 061/137] Remove the last "new" to reduce size --- libraries/MySensors/MyRFDriverRF69.cpp | 7 +++++-- libraries/MySensors/MySensor.cpp | 2 +- libraries/MySensors/MySensor.h | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/libraries/MySensors/MyRFDriverRF69.cpp b/libraries/MySensors/MyRFDriverRF69.cpp index 80e8874..c8e32ef 100644 --- a/libraries/MySensors/MyRFDriverRF69.cpp +++ b/libraries/MySensors/MyRFDriverRF69.cpp @@ -1,8 +1,11 @@ #include "MyRFDriver.h" #include "MyRFDriverRF69.h" -MyRFDriverRF69::MyRFDriverRF69() : MyRFDriver() { - radio = new RFM69(); +MyRFDriverRF69::MyRFDriverRF69() + : + MyRFDriver(), + radio() +{ } void MyRFDriverRF69::init() { diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index aab91ec..acd8bfb 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -107,7 +107,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b } void MySensor::setupRepeaterMode(){ - childNodeTable = new uint8_t[256]; +// childNodeTable = new uint8_t[256]; eeprom_read_block((void*)childNodeTable, (void*)EEPROM_ROUTES_ADDRESS, 256); } diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 01ca2b4..d139bda 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -260,7 +260,7 @@ class MySensor char convBuf[MAX_PAYLOAD*2+1]; #endif uint8_t failedTransmissions; - uint8_t *childNodeTable; // In memory buffer for routing information to other nodes. also stored in EEPROM + uint8_t childNodeTable[256]; // In memory buffer for routing information to other nodes. also stored in EEPROM void (*timeCallback)(unsigned long); // Callback for requested time messages void (*msgCallback)(const MyMessage &); // Callback for incoming messages from other nodes and gateway. From 5aebe80711e52d50a86926eb7ddc3702013fadc3 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 3 Mar 2015 00:24:13 +0100 Subject: [PATCH 062/137] Cleanup driver initialization --- libraries/MySensors/MyConfig.h | 20 +++++++++++++++---- libraries/MySensors/MyRFDriverNRF24.h | 4 ---- libraries/MySensors/MySensor.cpp | 9 ++++----- libraries/MySensors/MySensor.h | 8 ++++---- libraries/MySensors/MySigningDriver.cpp | 7 ++++++- libraries/MySensors/MySigningDriver.h | 9 ++++++++- .../MySensors/MySigningDriverAtsha204.cpp | 6 +++--- libraries/MySensors/MySigningDriverAtsha204.h | 2 +- .../MySensors/MySigningDriverAtsha204Soft.cpp | 7 ++++--- .../MySensors/MySigningDriverAtsha204Soft.h | 5 +++-- .../DallasTemperatureSensor.ino | 4 ---- .../EthernetGateway/EthernetGateway.ino | 9 ++++----- .../examples/EthernetGateway/GatewayUtil.h | 2 +- .../examples/MQTTGateway/MQTTGateway.ino | 3 --- .../examples/RelayActuator/RelayActuator.ino | 6 +----- .../SecureActuator/SecureActuator.ino | 12 +++++------ .../examples/SerialGateway/GatewayUtil.h | 2 +- .../examples/SerialGateway/SerialGateway.ino | 5 +---- libraries/MySensors/utility/RF24_config.h | 9 +++++---- 19 files changed, 68 insertions(+), 61 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 168a5fc..4ee4ac1 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -1,6 +1,6 @@ #ifndef MyConfig_h #define MyConfig_h - +#include /********************************** * Enable/Disable debug logging ***********************************/ @@ -15,13 +15,14 @@ // which might vary, especially in networks with many hops. 5s ought to be enough for anyone. #define MY_VERIFICATION_TIMEOUT_MS 5000 -// MySigningDriverAtsha204 settinga +// MySigningDriverAtsha204 default setting #define MY_ATSHA204_PIN 17 // A3 - pin where ATSHA204 is attached -// MySigningDriverAtsha204Soft settings +// MySigningDriverAtsha204Soft default settings #define MY_RANDOMSEED_PIN 7 // A7 - Pin used for random generation (do not connect anything to this) // Key to use for HMAC calculation in MySigningDriverAtsha204Soft (32 bytes) -#define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +#define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 /********************************** @@ -30,7 +31,18 @@ #define RF24_CE_PIN 9 #define RF24_CS_PIN 10 #define RF24_PA_LEVEL RF24_PA_MAX +#define RF24_CHANNEL 76 //RF channel for the sensor net, 0-127 +#define RF24_DATARATE RF24_250KBPS //RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps +#define RF24_BASE_RADIO_ID ((uint64_t)0xA8A8E1FC00LL) // This is also act as base value for sensor nodeId addresses. Change this (or channel) if you have more than one sensor network. +// Enable SOFTSPI for the W5100 Ethernet module +//#define SOFTSPI +#ifdef SOFTSPI + // Define the soft SPI pins used for NRF radio + const uint8_t SOFT_SPI_MISO_PIN = 16; + const uint8_t SOFT_SPI_MOSI_PIN = 15; + const uint8_t SOFT_SPI_SCK_PIN = 14; +#endif #endif diff --git a/libraries/MySensors/MyRFDriverNRF24.h b/libraries/MySensors/MyRFDriverNRF24.h index 21607e2..6fcf3f8 100644 --- a/libraries/MySensors/MyRFDriverNRF24.h +++ b/libraries/MySensors/MyRFDriverNRF24.h @@ -7,10 +7,6 @@ #include "utility/RF24.h" #include "utility/RF24_config.h" -#define RF24_CHANNEL 76 //RF channel for the sensor net, 0-127 -#define RF24_DATARATE RF24_250KBPS //RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps -#define RF24_BASE_RADIO_ID ((uint64_t)0xA8A8E1FC00LL) // This is also act as base value for sensor nodeId addresses. Change this (or channel) if you have more than one sensor network. - #define TO_ADDR(x) (RF24_BASE_RADIO_ID + x) #define WRITE_PIPE ((uint8_t)0) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index acd8bfb..0935791 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -45,12 +45,11 @@ MySensor::MySensor(MyRFDriver &_radio, MySigningDriver &_signer) } -void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId, bool requestSignatures) { +void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId) { Serial.begin(BAUD_RATE); repeaterMode = _repeaterMode; msgCallback = _msgCallback; failedTransmissions = 0; - requireSigning = requestSignatures; // Only gateway should use node id 0 isGateway = _nodeId == 0; @@ -137,7 +136,7 @@ void MySensor::setupNode() { present(NODE_SENSOR_ID, repeaterMode? S_ARDUINO_REPEATER_NODE : S_ARDUINO_NODE); // Notify gateway (and possibly controller) about the signing preferences of this node - sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(requireSigning)); + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(signer.requestSignatures())); // Send a configuration exchange request to controller // Node sends parent node. Controller answers with latest node configuration @@ -315,7 +314,7 @@ boolean MySensor::process() { // Before processing message, reject unsigned messages if signing is required and check signature (if it is signed and addressed to us) // Note that we do not care at all about any signature found if we do not require signing - if (requireSigning && msg.destination == nc.nodeId && mGetLength(msg) && + if (signer.requestSignatures() && msg.destination == nc.nodeId && mGetLength(msg) && (mGetCommand(msg) != C_INTERNAL || (msg.type != I_GET_NONCE_RESPONSE && msg.type != I_GET_NONCE && msg.type != I_REQUEST_SIGNING))) { if (!mGetSigned(msg)) return false; // Received an unsigned message but we do require signing. This message gets nowhere! else if (!signer.verifyMsg(msg)) { @@ -403,7 +402,7 @@ boolean MySensor::process() { // We do not currently want a gateway to require signing from all nodes in a network just because it wants one node // to sign it's messages if (isGateway) { - if (requireSigning && DO_SIGN(msg.sender)) + if (signer.requestSignatures() && DO_SIGN(msg.sender)) sendRoute(build(msg, nc.nodeId, msg.sender, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(true)); else sendRoute(build(msg, nc.nodeId, msg.sender, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(false)); diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index d139bda..cc15075 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -14,8 +14,10 @@ #include "Version.h" // Auto generated by bot #include "MyRFDriver.h" +#include "MyRFDriverNRF24.h" #include "MyParser.h" #include "MySigningDriver.h" +#include "MySigningDriverNone.h" #include "MyConfig.h" #include "MyMessage.h" #include @@ -79,7 +81,7 @@ class MySensor * Creates a new instance of Sensor class. * */ - MySensor(MyRFDriver &radio, MySigningDriver &signer); + MySensor(MyRFDriver &radio =*new MyRFDriverNRF24(), MySigningDriver &signer=*new MySigningDriverNone()); /** * Begin operation of the MySensors library @@ -89,10 +91,9 @@ class MySensor * @param nodeId The unique id (1-254) for this sensor. Default is AUTO(255) which means sensor tries to fetch an id from controller. * @param repeaterMode Activate repeater mode. This node will forward messages to other nodes in the radio network. Make sure to call process() regularly. Default in false * @param parentNodeId Use this to force node to always communicate with a certain parent node. Default is AUTO which means node automatically tries to find a parent. - * @param requestSignatures Set this to true if you want destination node to sign all messages sent to this node. Default is not to require signing. */ - void begin(void (* msgCallback)(const MyMessage &)=NULL, uint8_t nodeId=AUTO, boolean repeaterMode=false, uint8_t parentNodeId=AUTO, bool requestSignatures=false); + void begin(void (* msgCallback)(const MyMessage &)=NULL, uint8_t nodeId=AUTO, boolean repeaterMode=false, uint8_t parentNodeId=AUTO); /** * Return the nodes nodeId. @@ -242,7 +243,6 @@ class MySensor bool repeaterMode; bool autoFindParent; bool isGateway; - bool requireSigning; uint16_t doSign[16]; // Bitfield indicating which sensors require signed communication MyMessage msg; // Buffer for incoming messages. diff --git a/libraries/MySensors/MySigningDriver.cpp b/libraries/MySensors/MySigningDriver.cpp index b109a3f..aa718fc 100644 --- a/libraries/MySensors/MySigningDriver.cpp +++ b/libraries/MySensors/MySigningDriver.cpp @@ -1,4 +1,9 @@ #include "MySigningDriver.h" -MySigningDriver::MySigningDriver() { +MySigningDriver::MySigningDriver(bool requestSignatures) : _requestSignatures(requestSignatures) { +} + + +bool MySigningDriver::requestSignatures() { + return _requestSignatures; } diff --git a/libraries/MySensors/MySigningDriver.h b/libraries/MySensors/MySigningDriver.h index 28a75ea..ebabde8 100644 --- a/libraries/MySensors/MySigningDriver.h +++ b/libraries/MySensors/MySigningDriver.h @@ -16,7 +16,11 @@ public: // MySigningDriver constructor. // Different parameters would be needed depending on signing backend (e.g. pins connected etc.). // Keeping these parameters as #define's in MyConfig to streamline the driver interface. - MySigningDriver(); + // @param requestSignatures Set this to true if you want destination node to sign all messages sent to this node. Default is not to require signing. + MySigningDriver(bool requestSignatures=false); + + // Returns the current requestSignature setting + bool requestSignatures(); // Stores signing identifier and a new nonce in provided message for signing operations. // All space in message payload buffer is used for signing identifier and nonce. @@ -55,6 +59,9 @@ public: // This ends a signing operation at the receiving side so implementation is expected to do any // deinitializations and enter a power saving state within this call. virtual bool verifyMsg(MyMessage &msg) = 0; + + public: + bool _requestSignatures; }; #endif diff --git a/libraries/MySensors/MySigningDriverAtsha204.cpp b/libraries/MySensors/MySigningDriverAtsha204.cpp index fab6942..401a82c 100644 --- a/libraries/MySensors/MySigningDriverAtsha204.cpp +++ b/libraries/MySensors/MySigningDriverAtsha204.cpp @@ -36,10 +36,10 @@ static void DEBUG_ATSHA_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) #endif -MySigningDriverAtsha204::MySigningDriverAtsha204() +MySigningDriverAtsha204::MySigningDriverAtsha204(bool requestSignatures, uint8_t atshaPin) : - MySigningDriver(), - atsha204(MY_ATSHA204_PIN), + MySigningDriver(requestSignatures), + atsha204(atshaPin), verification_ongoing(false) { // We set the part of the 32-byte nonce that does not fit into a message to 0xAA diff --git a/libraries/MySensors/MySigningDriverAtsha204.h b/libraries/MySensors/MySigningDriverAtsha204.h index 57bb2f3..8da91ae 100644 --- a/libraries/MySensors/MySigningDriverAtsha204.h +++ b/libraries/MySensors/MySigningDriverAtsha204.h @@ -20,7 +20,7 @@ class MySigningDriverAtsha204 : public MySigningDriver { public: - MySigningDriverAtsha204(); + MySigningDriverAtsha204(bool requestSignatures=true, uint8_t atshaPin = MY_ATSHA204_PIN); bool getNonce(MyMessage &msg); bool checkTimer(void); bool putNonce(MyMessage &msg); diff --git a/libraries/MySensors/MySigningDriverAtsha204Soft.cpp b/libraries/MySensors/MySigningDriverAtsha204Soft.cpp index b57ab11..c9f6e44 100644 --- a/libraries/MySensors/MySigningDriverAtsha204Soft.cpp +++ b/libraries/MySensors/MySigningDriverAtsha204Soft.cpp @@ -40,9 +40,10 @@ static void DEBUG_ATSHASOFT_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) #define DEBUG_ATSHASOFT_PRINTBUF(str, buf, sz) #endif -MySigningDriverAtsha204Soft::MySigningDriverAtsha204Soft() +MySigningDriverAtsha204Soft::MySigningDriverAtsha204Soft(bool requestSignatures, uint8_t randomseedPin) : - MySigningDriver(), + MySigningDriver(requestSignatures), + rndPin(randomseedPin), hmacKey({MY_HMAC_KEY}), verification_ongoing(false), Sha256() @@ -54,7 +55,7 @@ MySigningDriverAtsha204Soft::MySigningDriverAtsha204Soft() bool MySigningDriverAtsha204Soft::getNonce(MyMessage &msg) { // Set randomseed - randomSeed(analogRead(MY_RANDOMSEED_PIN)); + randomSeed(analogRead(rndPin)); for (int i = 0; i < MAX_PAYLOAD; i++) { current_nonce[i] = random(255); diff --git a/libraries/MySensors/MySigningDriverAtsha204Soft.h b/libraries/MySensors/MySigningDriverAtsha204Soft.h index 014589a..eef0a31 100644 --- a/libraries/MySensors/MySigningDriverAtsha204Soft.h +++ b/libraries/MySensors/MySigningDriverAtsha204Soft.h @@ -24,11 +24,11 @@ // Because it is completly software based, the quality of the generated random numbers // is weaker though. Random numbers are generated using the Arduino library and seed // is sampled from an analog pin. This pin should unconnected in the hardware. -// The pin is selected using RANDOMSEED_PIN in MyConfig.h. +// The pin is selected using MY_RANDOMSEED_PIN in MyConfig.h. class MySigningDriverAtsha204Soft : public MySigningDriver { public: - MySigningDriverAtsha204Soft(); + MySigningDriverAtsha204Soft(bool requestSignatures=true, uint8_t randomseedPin = MY_RANDOMSEED_PIN); bool getNonce(MyMessage &msg); bool checkTimer(void); bool putNonce(MyMessage &msg); @@ -41,6 +41,7 @@ private: uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH]; uint8_t temp_message[32]; uint8_t hmacKey[32]; + uint8_t rndPin; uint8_t* hmac; bool calculateSignature(MyMessage &msg); }; diff --git a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino index a52c49d..3c6c2c0 100644 --- a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino @@ -4,10 +4,6 @@ #include #include -#ifndef MYSENSORS_SENSOR -#error Please switch to MYSENSORS_SENSOR in MyConfig.h -#endif - #define ONE_WIRE_BUS 3 // Pin where dallase sensor is connected #define MAX_ATTACHED_DS18B20 16 unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index f0f941c..26fe33f 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -17,7 +17,7 @@ * * * COMPILING WIZNET (W5100) ETHERNET MODULE - * > Edit RF24_config.h in (libraries\MySensors\utility) to enable softspi (remove // before "#define SOFTSPI"). + * > Edit MyConfig.h in (libraries\MySensors\) to enable softspi (remove // before "#define SOFTSPI"). * * COMPILING ENC28J60 ETHERNET MODULE * > Use Arduino IDE 1.5.7 (or later) @@ -42,18 +42,17 @@ #include // This include can be removed when using UIPEthernet module #include + +#include #include #include #include #include #include "GatewayUtil.h" -#ifndef MYSENSORS_ETHERNET_GATEWAY -#error Please switch to MYSENSORS_ETHERNET_GATEWAY in MyConfig.h -#endif // Use this if you have attached a Ethernet ENC28J60 shields -//#include +// #include // Use this for WizNET W5100 module and Arduino Ethernet Shield #include diff --git a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h index 109f330..fa5f1b6 100644 --- a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h @@ -23,7 +23,7 @@ volatile uint8_t countErr; boolean inclusionMode; // Keeps track on inclusion mode void (*serial)(const char *fmt, ... ); -MyParserClass parser; +MyParserSerial parser; void setInclusionMode(boolean newMode); void txBlink(uint8_t cnt); diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index a9a497d..bea3ef4 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -62,9 +62,6 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway #include #include "MyMQTT.h" -#ifndef MYSENSORS_MQTT_GATEWAY -#error Please switch to MYSENSORS_MQTT_GATEWAY in MyConfig.h -#endif #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled #define INCLUSION_MODE_PIN 3 // Digital pin used for inclusion mode button diff --git a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino index c0e8a7c..3f0e94f 100644 --- a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino +++ b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino @@ -1,8 +1,6 @@ // Example sketch showing how to control physical relays. // This example will remember relay state even after power failure. -#include -#include #include #include @@ -11,9 +9,7 @@ #define RELAY_ON 1 // GPIO value to write to turn on attached relay #define RELAY_OFF 0 // GPIO value to write to turn off attached relay -MyRFDriverNRF24 radio; // NRFRF24L01 radio driver -MySigningDriverNone signer; // Message signing disabled -MySensor gw(radio, signer); +MySensor gw; void setup() { diff --git a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino index c86ff49..65f0fe7 100644 --- a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino +++ b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino @@ -1,24 +1,24 @@ // Example sketch showing how to securely control locks. // This example will remember lock state even after power failure. +#include +#include #include #include -#ifndef MYSENSORS_SENSOR -#error Please switch to MYSENSORS_SENSOR in MyConfig.h -#endif - #define LOCK_1 3 // Arduino Digital I/O pin number for first lock (second on pin+1 etc) #define NOF_LOCKS 1 // Total number of attached locks #define LOCK_LOCK 1 // GPIO value to write to lock attached lock #define LOCK_UNLOCK 0 // GPIO value to write to unlock attached lock -MySensor gw; +MyRFDriverNRF24 radio; // NRFRF24L01 radio driver +MySigningDriverAtsha204Soft signer; // Message signing driver +MySensor gw(radio, signer); void setup() { // Initialize library and add callback for incoming messages (signing is required) - gw.begin(incomingMessage, AUTO, true, AUTO, true); + gw.begin(incomingMessage, AUTO, true, AUTO); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Secure Lock", "1.0"); diff --git a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h index 109f330..fa5f1b6 100644 --- a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h @@ -23,7 +23,7 @@ volatile uint8_t countErr; boolean inclusionMode; // Keeps track on inclusion mode void (*serial)(const char *fmt, ... ); -MyParserClass parser; +MyParserSerial parser; void setInclusionMode(boolean newMode); void txBlink(uint8_t cnt); diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index 6ee18a4..dddacdb 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -24,16 +24,13 @@ #define NO_PORTB_PINCHANGES #include +#include #include #include #include #include #include "GatewayUtil.h" -#ifndef MYSENSORS_SERIAL_GATEWAY -#error Please switch to MYSENSORS_SERIAL_GATEWAY in MyConfig.h -#endif - #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled #define INCLUSION_MODE_PIN 3 // Digital pin used for inclusion mode button #define RADIO_ERROR_LED_PIN 4 // Error led pin diff --git a/libraries/MySensors/utility/RF24_config.h b/libraries/MySensors/utility/RF24_config.h index 3c394c7..2addc27 100755 --- a/libraries/MySensors/utility/RF24_config.h +++ b/libraries/MySensors/utility/RF24_config.h @@ -11,6 +11,7 @@ #ifndef __RF24_CONFIG_H__ #define __RF24_CONFIG_H__ + #include #if ARDUINO < 100 #include @@ -39,10 +40,10 @@ #define _SPI uspi #elif defined SOFTSPI // change these pins to your liking - // - const uint8_t SOFT_SPI_MISO_PIN = 16; - const uint8_t SOFT_SPI_MOSI_PIN = 15; - const uint8_t SOFT_SPI_SCK_PIN = 14; + //const uint8_t SOFT_SPI_MISO_PIN = 16; // <-- Moved to MyConfig.h + //const uint8_t SOFT_SPI_MOSI_PIN = 15; // <-- Moved to MyConfig.h + //const uint8_t SOFT_SPI_SCK_PIN = 14; // <-- Moved to MyConfig.h + const uint8_t SPI_MODE = 0; #define _SPI spi From 7d67ad5c829a1e5bff760a6fe12a2cb7d55cca03 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 4 Mar 2015 19:24:13 +0100 Subject: [PATCH 063/137] Add new sensor type S_MULTIMETER To be used with V_CURRENT, V_VOLTAGE, V_IMPEDANCE --- libraries/MySensors/MyMessage.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index fcc0540..c182f34 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -55,7 +55,7 @@ typedef enum { S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, - S_SCENE_CONTROLLER,S_COLOR + S_SCENE_CONTROLLER,S_COLOR, S_MULTMETER } mysensor_sensor; // Type of data stream (for streamed message) From 89076d58d1cfcea8c815ccc3aaa156aeb4238317 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 4 Mar 2015 20:17:53 +0100 Subject: [PATCH 064/137] Fix spelling error. --- libraries/MySensors/MyMessage.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index c182f34..2616c32 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -55,7 +55,7 @@ typedef enum { S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, - S_SCENE_CONTROLLER,S_COLOR, S_MULTMETER + S_SCENE_CONTROLLER,S_COLOR, S_MULTIMETER } mysensor_sensor; // Type of data stream (for streamed message) From 79be69b08d36d5928b18d40ba036969a8d35aaba Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 7 Mar 2015 00:34:42 +0100 Subject: [PATCH 065/137] Support for gateways to request signed messages Various fixes and tweaks to permit a gateway to request signatures from nodes. The following messages will not be signed (nor verified): * All signing-related handshake messages * All ID-related handshake messages * All ACKs An important change is that the polarity for the signing request flags stored in EEPROM has changed. '0' now means signing required. This ensures that if the "ClearEepromConfig" sketch is executed, signing requests will be turned off by default. As a consequence, it is recommended to clear EEPROM if signing will be used to ensure all nodes default to a non-signing state. --- libraries/MySensors/MySensor.cpp | 46 +++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 0935791..1eb28d9 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -14,9 +14,9 @@ #define DISTANCE_INVALID (0xFF) // Macros for manipulating signing requirement table -#define DO_SIGN(node) (doSign[node>>4]&(node%16)) -#define SET_SIGN(node) (doSign[node>>4]|=(node%16)) -#define CLEAR_SIGN(node) (doSign[node>>4]&=~(node%16)) +#define DO_SIGN(node) (node == 0 ? (~doSign[0]&1) : (~doSign[node>>4]&(node%16))) +#define SET_SIGN(node) (node == 0 ? (doSign[0]&=~1) : (doSign[node>>4]&=~(node%16))) +#define CLEAR_SIGN(node) (node == 0 ? (doSign[0]|=1) : (doSign[node>>4]|=(node%16))) // Inline function and macros static inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, uint8_t sensor, uint8_t command, uint8_t type, bool enableAck) { @@ -132,12 +132,17 @@ void MySensor::setupNode() { // Present node and request config if (!isGateway && nc.nodeId != AUTO) { - // Send presentation for this radio node (attach - present(NODE_SENSOR_ID, repeaterMode? S_ARDUINO_REPEATER_NODE : S_ARDUINO_NODE); - // Notify gateway (and possibly controller) about the signing preferences of this node sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(signer.requestSignatures())); + // If we do require signing, wait for the gateway to tell us how it perfer us to transmit our messages + if (signer.requestSignatures()) { + wait(2000); + } + + // Send presentation for this radio node (attach + present(NODE_SENSOR_ID, repeaterMode? S_ARDUINO_REPEATER_NODE : S_ARDUINO_NODE); + // Send a configuration exchange request to controller // Node sends parent node. Controller answers with latest node configuration // which is picked up in process() @@ -185,9 +190,12 @@ boolean MySensor::sendRoute(MyMessage &message) { mSetVersion(message, PROTOCOL_VERSION); - // If destination is known to require signed messages and we are the sender, sign this message unless it is an ACK or a signing handshake message + // If destination is known to require signed messages and we are the sender, sign this message unless it is an ACK or a handshake message if (DO_SIGN(message.destination) && message.sender == nc.nodeId && !mGetAck(message) && mGetLength(msg) && - (mGetCommand(message) != C_INTERNAL || (message.type != I_GET_NONCE && message.type != I_GET_NONCE_RESPONSE && message.type != I_REQUEST_SIGNING))) { + (mGetCommand(message) != C_INTERNAL || + (message.type != I_GET_NONCE && message.type != I_GET_NONCE_RESPONSE && message.type != I_REQUEST_SIGNING && + message.type != I_ID_REQUEST && message.type != I_ID_RESPONSE && + message.type != I_FIND_PARENT && message.type != I_FIND_PARENT_RESPONSE))) { if (!sign(message)) { debug(PSTR("Message signing failed\n")); return false; @@ -313,10 +321,16 @@ boolean MySensor::process() { uint8_t len = radio.receive((uint8_t *)&msg); // Before processing message, reject unsigned messages if signing is required and check signature (if it is signed and addressed to us) - // Note that we do not care at all about any signature found if we do not require signing - if (signer.requestSignatures() && msg.destination == nc.nodeId && mGetLength(msg) && - (mGetCommand(msg) != C_INTERNAL || (msg.type != I_GET_NONCE_RESPONSE && msg.type != I_GET_NONCE && msg.type != I_REQUEST_SIGNING))) { - if (!mGetSigned(msg)) return false; // Received an unsigned message but we do require signing. This message gets nowhere! + // Note that we do not care at all about any signature found if we do not require signing, nor do we care about ACKs (they are never signed) + if (signer.requestSignatures() && msg.destination == nc.nodeId && mGetLength(msg) && !mGetAck(msg) && + (mGetCommand(msg) != C_INTERNAL || + (msg.type != I_GET_NONCE_RESPONSE && msg.type != I_GET_NONCE && msg.type != I_REQUEST_SIGNING && + msg.type != I_ID_REQUEST && msg.type != I_ID_RESPONSE && + msg.type != I_FIND_PARENT && msg.type != I_FIND_PARENT_RESPONSE))) { + if (!mGetSigned(msg)) { + debug(PSTR("Got unsigned message that should have been signed\n")); + return false; + } else if (!signer.verifyMsg(msg)) { debug(PSTR("Message verification failed\n")); return false; // This signed message has been tampered with! @@ -383,10 +397,9 @@ boolean MySensor::process() { return false; } else if (type == I_GET_NONCE) { if (signer.getNonce(msg)) { - sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_GET_NONCE_RESPONSE, false)); - } else { - return false; + sendRoute(build(msg, nc.nodeId, msg.sender, NODE_SENSOR_ID, C_INTERNAL, I_GET_NONCE_RESPONSE, false)); } + return false; // Nonce exchange is an internal MySensor protocol message, no need to inform caller about this } else if (type == I_REQUEST_SIGNING) { if (msg.getBool()) { // We received an indicator that the sender require us to sign all messages we send to it @@ -407,6 +420,9 @@ boolean MySensor::process() { else sendRoute(build(msg, nc.nodeId, msg.sender, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(false)); } + return false; // Signing request is an internal MySensor protocol message, no need to inform caller about this + } else if (type == I_GET_NONCE_RESPONSE) { + return true; // Just pass along nonce silently (no need to call callback for these) } else if (sender == GATEWAY_ADDRESS) { bool isMetric; From a21715d4159d7afcac38145c7151d1eae0c88cbb Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sun, 8 Mar 2015 11:29:57 +0100 Subject: [PATCH 066/137] SHA204 personalizer updated to handle HMAC key better HMAC key is now configured and printed exactly as it is set in MyConfig.h. This makes it easier to move the key around. --- libraries/MySensors/MyConfig.h | 2 +- .../Sha204Personalizer/Sha204Personalizer.ino | 16 +++++++--------- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 4ee4ac1..fd6358c 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -22,7 +22,7 @@ #define MY_RANDOMSEED_PIN 7 // A7 - Pin used for random generation (do not connect anything to this) // Key to use for HMAC calculation in MySigningDriverAtsha204Soft (32 bytes) #define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 /********************************** diff --git a/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino b/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino index a39ceeb..066c834 100644 --- a/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino +++ b/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino @@ -57,12 +57,9 @@ #endif #ifdef USER_KEY_DATA -const uint8_t user_key_data[32] = { -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, -0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 -}; +#define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +const uint8_t user_key_data[32] = {MY_HMAC_KEY}; #endif const int sha204Pin = ATSHA204_PIN; @@ -796,7 +793,7 @@ void setup() } #endif //not SKIP_UART_CONFIRMATION #else //LOCK_CONFIGURATION - Serial.println(F("Dry-run. Configuration not locked. Define LOCK_CONFIGURATION to lock for real.")); + Serial.println(F("Configuration not locked. Define LOCK_CONFIGURATION to lock for real.")); #endif } else @@ -833,6 +830,7 @@ void setup() Serial.println(F("Key is not randomized (configuration not locked):")); } #endif + Serial.print("#define MY_HMAC_KEY "); for (int i=0; i<32; i++) { Serial.print("0x"); @@ -842,7 +840,7 @@ void setup() } Serial.print(key[i], HEX); if (i < 31) Serial.print(','); - if (!((i+1) % 8)) Serial.println(); + if (i+1 == 16) Serial.print("\\\n "); } Serial.println(); @@ -937,7 +935,7 @@ void setup() } #endif //not SKIP_UART_CONFIRMATION #else //LOCK_DATA - Serial.println(F("Dry-run. Data not locked. Define LOCK_DATA to lock for real.")); + Serial.println(F("Data not locked. Define LOCK_DATA to lock for real.")); #endif } else From 7e6aa8bda8466a42b2cbb59e0cdbe54f502e2eec Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 9 Mar 2015 22:58:05 +0100 Subject: [PATCH 067/137] Add the default constructors to gateway sketches --- libraries/MySensors/MyConfig.h | 1 + .../examples/EthernetGateway/EthernetGateway.ino | 10 ++++++++-- .../MySensors/examples/MQTTGateway/MQTTGateway.ino | 10 +++++++++- .../MySensors/examples/SerialGateway/SerialGateway.ino | 9 ++++++++- 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index fd6358c..b259a1c 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -31,6 +31,7 @@ #define RF24_CE_PIN 9 #define RF24_CS_PIN 10 #define RF24_PA_LEVEL RF24_PA_MAX +#define RF24_PA_LEVEL_GW RF24_PA_LOW #define RF24_CHANNEL 76 //RF channel for the sensor net, 0-127 #define RF24_DATARATE RF24_250KBPS //RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps #define RF24_BASE_RADIO_ID ((uint64_t)0xA8A8E1FC00LL) // This is also act as base value for sensor nodeId addresses. Change this (or channel) if you have more than one sensor network. diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 26fe33f..def707b 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -43,6 +43,8 @@ #include // This include can be removed when using UIPEthernet module #include +#include +#include #include #include #include @@ -69,8 +71,12 @@ #define RADIO_TX_LED_PIN 9 // the PCB, on board LED -MySensor gw; - +// NRFRF24L01 radio driver (set low transmit power by default) +MyRFDriverNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +// Message signing driver (none default) +MySigningDriverNone signer; +// Construct MySensors library +MySensor gw(radio, signer); #define IP_PORT 5003 // The port you want to open IPAddress myIp (192, 168, 178, 66); // Configure your static ip-address here COMPILE ERROR HERE? Use Arduino IDE 1.5.7 or later! diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index bea3ef4..706ca3c 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -56,6 +56,8 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway */ +#include +#include #include #include #include @@ -89,7 +91,13 @@ uint8_t TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You ////////////////////////////////////////////////////////////////// -MySensor gw; +// NRFRF24L01 radio driver (set low transmit power by default) +MyRFDriverNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +// Message signing driver (none default) +MySigningDriverNone signer; +// Construct MySensors library +MySensor gw(radio, signer); + EthernetServer server = EthernetServer(TCP_PORT); MyMessage msg; char convBuf[MAX_PAYLOAD*2+1]; diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index dddacdb..c178b19 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -23,6 +23,8 @@ #define NO_PORTB_PINCHANGES +#include +#include #include #include #include @@ -38,7 +40,12 @@ #define RADIO_TX_LED_PIN 5 // the PCB, on board LED -MySensor gw; +// NRFRF24L01 radio driver (set low transmit power by default) +MyRFDriverNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +// Message signing driver (none default) +MySigningDriverNone signer; +// Construct MySensors library +MySensor gw(radio, signer); char inputString[MAX_RECEIVE_LENGTH] = ""; // A string to hold incoming commands from serial/ethernet interface int inputPos = 0; From 7a1cdd06e1c883e62c6f4e6e0232b4a8576c26ac Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 9 Mar 2015 23:45:05 +0100 Subject: [PATCH 068/137] Rename RFDriver to Transport --- libraries/MySensors/MyParserSerial.cpp | 2 +- libraries/MySensors/MyRFDriver.cpp | 4 ---- libraries/MySensors/MySensor.cpp | 2 +- libraries/MySensors/MySensor.h | 8 +++---- libraries/MySensors/MyTransport.cpp | 4 ++++ .../MySensors/{MyRFDriver.h => MyTransport.h} | 10 ++++----- ...RFDriverNRF24.cpp => MyTransportNRF24.cpp} | 22 +++++++++---------- .../{MyRFDriverNRF24.h => MyTransportNRF24.h} | 10 ++++----- ...MyRFDriverRF69.cpp => MyTransportRF69.cpp} | 22 +++++++++---------- .../{MyRFDriverRF69.h => MyTransportRF69.h} | 10 ++++----- .../EthernetGateway/EthernetGateway.ino | 4 ++-- .../examples/EthernetGateway/GatewayUtil.h | 2 +- .../examples/MQTTGateway/MQTTGateway.ino | 4 ++-- .../SecureActuator/SecureActuator.ino | 4 ++-- .../examples/SerialGateway/GatewayUtil.h | 2 +- .../examples/SerialGateway/SerialGateway.ino | 4 ++-- 16 files changed, 57 insertions(+), 57 deletions(-) delete mode 100644 libraries/MySensors/MyRFDriver.cpp create mode 100644 libraries/MySensors/MyTransport.cpp rename libraries/MySensors/{MyRFDriver.h => MyTransport.h} (94%) rename libraries/MySensors/{MyRFDriverNRF24.cpp => MyTransportNRF24.cpp} (73%) rename libraries/MySensors/{MyRFDriverNRF24.h => MyTransportNRF24.h} (71%) rename libraries/MySensors/{MyRFDriverRF69.cpp => MyTransportRF69.cpp} (63%) rename libraries/MySensors/{MyRFDriverRF69.h => MyTransportRF69.h} (89%) diff --git a/libraries/MySensors/MyParserSerial.cpp b/libraries/MySensors/MyParserSerial.cpp index 8c020b5..9c1aa88 100644 --- a/libraries/MySensors/MyParserSerial.cpp +++ b/libraries/MySensors/MyParserSerial.cpp @@ -1,6 +1,6 @@ #include "MyParser.h" #include "MyParserSerial.h" -#include "MyRFDriver.h" +#include "MyTransport.h" MyParserSerial::MyParserSerial() : MyParser() {} diff --git a/libraries/MySensors/MyRFDriver.cpp b/libraries/MySensors/MyRFDriver.cpp deleted file mode 100644 index cf669a0..0000000 --- a/libraries/MySensors/MyRFDriver.cpp +++ /dev/null @@ -1,4 +0,0 @@ -#include "MyRFDriver.h" - -MyRFDriver::MyRFDriver() { -} diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 1eb28d9..e34b22f 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -37,7 +37,7 @@ static inline bool isValidDistance( const uint8_t distance ) { return distance != DISTANCE_INVALID; } -MySensor::MySensor(MyRFDriver &_radio, MySigningDriver &_signer) +MySensor::MySensor(MyTransport &_radio, MySigningDriver &_signer) : radio(_radio), signer(_signer) diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index cc15075..b3a451d 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -13,8 +13,8 @@ #define MySensor_h #include "Version.h" // Auto generated by bot -#include "MyRFDriver.h" -#include "MyRFDriverNRF24.h" +#include "MyTransport.h" +#include "MyTransportNRF24.h" #include "MyParser.h" #include "MySigningDriver.h" #include "MySigningDriverNone.h" @@ -81,7 +81,7 @@ class MySensor * Creates a new instance of Sensor class. * */ - MySensor(MyRFDriver &radio =*new MyRFDriverNRF24(), MySigningDriver &signer=*new MySigningDriverNone()); + MySensor(MyTransport &radio =*new MyTransportNRF24(), MySigningDriver &signer=*new MySigningDriverNone()); /** * Begin operation of the MySensors library @@ -249,7 +249,7 @@ class MySensor MyMessage tmpMsg ; // Buffer for temporary messages (acks and nonces among others). MyMessage msgSign; // Buffer for message to sign. - MyRFDriver& radio; + MyTransport& radio; MySigningDriver& signer; void setupRepeaterMode(); diff --git a/libraries/MySensors/MyTransport.cpp b/libraries/MySensors/MyTransport.cpp new file mode 100644 index 0000000..56cfdf9 --- /dev/null +++ b/libraries/MySensors/MyTransport.cpp @@ -0,0 +1,4 @@ +#include "MyTransport.h" + +MyTransport::MyTransport() { +} diff --git a/libraries/MySensors/MyRFDriver.h b/libraries/MySensors/MyTransport.h similarity index 94% rename from libraries/MySensors/MyRFDriver.h rename to libraries/MySensors/MyTransport.h index 8157af1..5c7b728 100644 --- a/libraries/MySensors/MyRFDriver.h +++ b/libraries/MySensors/MyTransport.h @@ -1,5 +1,5 @@ -#ifndef MyRFDriver_h -#define MyRFDriver_h +#ifndef MyTransport_h +#define MyTransport_h #include @@ -16,13 +16,13 @@ #define GATEWAY_ADDRESS ((uint8_t)0) #define BROADCAST_ADDRESS ((uint8_t)0xFF) -class MyRFDriver +class MyTransport { public: - // MyRFDriver constructor + // MyTransport constructor // different parameters would be needed depending on radio module (e.g. pins connected etc.) // keeping these parameters as #define's in MyConfig to streamline the driver interface - MyRFDriver(); + MyTransport(); // init() // different parameters would be needed depending on radio module (e.g. channel, power, crc, etc.) // keeping these parameters as #define's in MyConfig to streamline the driver interface diff --git a/libraries/MySensors/MyRFDriverNRF24.cpp b/libraries/MySensors/MyTransportNRF24.cpp similarity index 73% rename from libraries/MySensors/MyRFDriverNRF24.cpp rename to libraries/MySensors/MyTransportNRF24.cpp index 9b4fe45..9cc63fb 100644 --- a/libraries/MySensors/MyRFDriverNRF24.cpp +++ b/libraries/MySensors/MyTransportNRF24.cpp @@ -1,15 +1,15 @@ -#include "MyRFDriver.h" -#include "MyRFDriverNRF24.h" +#include "MyTransport.h" +#include "MyTransportNRF24.h" -MyRFDriverNRF24::MyRFDriverNRF24(uint8_t ce, uint8_t cs, uint8_t paLevel) +MyTransportNRF24::MyTransportNRF24(uint8_t ce, uint8_t cs, uint8_t paLevel) : - MyRFDriver(), + MyTransport(), rf24(ce, cs), _paLevel(paLevel) { } -void MyRFDriverNRF24::init() { +void MyTransportNRF24::init() { // Start up the radio library rf24.begin(); @@ -31,18 +31,18 @@ void MyRFDriverNRF24::init() { rf24.openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); } -void MyRFDriverNRF24::setAddress(uint8_t address) { +void MyTransportNRF24::setAddress(uint8_t address) { _address = address; rf24.openReadingPipe(WRITE_PIPE, TO_ADDR(address)); rf24.openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(address)); rf24.startListening(); } -uint8_t MyRFDriverNRF24::getAddress() { +uint8_t MyTransportNRF24::getAddress() { return _address; } -bool MyRFDriverNRF24::send(uint8_t to, const void* data, uint8_t len) { +bool MyTransportNRF24::send(uint8_t to, const void* data, uint8_t len) { // Make sure radio has powered up rf24.powerUp(); rf24.stopListening(); @@ -52,7 +52,7 @@ bool MyRFDriverNRF24::send(uint8_t to, const void* data, uint8_t len) { return ok; } -bool MyRFDriverNRF24::available(uint8_t *to) { +bool MyTransportNRF24::available(uint8_t *to) { uint8_t pipe = 255; boolean avail = rf24.available(&pipe); if (pipe == CURRENT_NODE_PIPE) @@ -62,12 +62,12 @@ bool MyRFDriverNRF24::available(uint8_t *to) { return (rf24.available() && pipe < 6); } -uint8_t MyRFDriverNRF24::receive(void* data) { +uint8_t MyTransportNRF24::receive(void* data) { uint8_t len = rf24.getDynamicPayloadSize(); rf24.read(data, len); return len; } -void MyRFDriverNRF24::powerDown() { +void MyTransportNRF24::powerDown() { rf24.powerDown(); } diff --git a/libraries/MySensors/MyRFDriverNRF24.h b/libraries/MySensors/MyTransportNRF24.h similarity index 71% rename from libraries/MySensors/MyRFDriverNRF24.h rename to libraries/MySensors/MyTransportNRF24.h index 6fcf3f8..c5ac75e 100644 --- a/libraries/MySensors/MyRFDriverNRF24.h +++ b/libraries/MySensors/MyTransportNRF24.h @@ -1,8 +1,8 @@ -#ifndef MyRFDriverNRF24_h -#define MyRFDriverNRF24_h +#ifndef MyTransportNRF24_h +#define MyTransportNRF24_h #include "MyConfig.h" -#include "MyRFDriver.h" +#include "MyTransport.h" #include #include "utility/RF24.h" #include "utility/RF24_config.h" @@ -13,10 +13,10 @@ #define CURRENT_NODE_PIPE ((uint8_t)1) #define BROADCAST_PIPE ((uint8_t)2) -class MyRFDriverNRF24 : public MyRFDriver +class MyTransportNRF24 : public MyTransport { public: - MyRFDriverNRF24(uint8_t ce=RF24_CE_PIN, uint8_t cs=RF24_CS_PIN, uint8_t paLevel=RF24_PA_LEVEL); + MyTransportNRF24(uint8_t ce=RF24_CE_PIN, uint8_t cs=RF24_CS_PIN, uint8_t paLevel=RF24_PA_LEVEL); void init(); void setAddress(uint8_t address); uint8_t getAddress(); diff --git a/libraries/MySensors/MyRFDriverRF69.cpp b/libraries/MySensors/MyTransportRF69.cpp similarity index 63% rename from libraries/MySensors/MyRFDriverRF69.cpp rename to libraries/MySensors/MyTransportRF69.cpp index c8e32ef..b55ce14 100644 --- a/libraries/MySensors/MyRFDriverRF69.cpp +++ b/libraries/MySensors/MyTransportRF69.cpp @@ -1,14 +1,14 @@ -#include "MyRFDriver.h" -#include "MyRFDriverRF69.h" +#include "MyTransport.h" +#include "MyTransportRF69.h" -MyRFDriverRF69::MyRFDriverRF69() +MyTransportRF69::MyTransportRF69() : - MyRFDriver(), + MyTransport(), radio() { } -void MyRFDriverRF69::init() { +void MyTransportRF69::init() { // Start up the radio library radio->initialize(FREQUENCY,_address,NETWORKID); #ifdef IS_RFM69HW @@ -18,21 +18,21 @@ void MyRFDriverRF69::init() { } -void MyRFDriverRF69::setAddress(uint8_t address) { +void MyTransportRF69::setAddress(uint8_t address) { _address = address; radio->setAddress(address); } -uint8_t MyRFDriverRF69::getAddress() { +uint8_t MyTransportRF69::getAddress() { return _address; } -bool MyRFDriverRF69::send(uint8_t to, const void* data, uint8_t len) { +bool MyTransportRF69::send(uint8_t to, const void* data, uint8_t len) { // Make sure radio has powered up return radio->sendWithRetry(to,data,len); } -bool MyRFDriverRF69::available(uint8_t *to) { +bool MyTransportRF69::available(uint8_t *to) { if (radio->TARGETID == BROADCAST_ADDRESS) *to = BROADCAST_ADDRESS; else @@ -40,7 +40,7 @@ bool MyRFDriverRF69::available(uint8_t *to) { return radio->receiveDone(); } -uint8_t MyRFDriverRF69::receive(void* data) { +uint8_t MyTransportRF69::receive(void* data) { // for (byte i = 0; i < radio->DATALEN; i++){ // data[i]= (void)radio->DATA[i]; // } @@ -52,6 +52,6 @@ uint8_t MyRFDriverRF69::receive(void* data) { return radio->DATALEN; } -void MyRFDriverRF69::powerDown() { +void MyTransportRF69::powerDown() { radio->sleep(); } diff --git a/libraries/MySensors/MyRFDriverRF69.h b/libraries/MySensors/MyTransportRF69.h similarity index 89% rename from libraries/MySensors/MyRFDriverRF69.h rename to libraries/MySensors/MyTransportRF69.h index 256cc4d..687259d 100644 --- a/libraries/MySensors/MyRFDriverRF69.h +++ b/libraries/MySensors/MyTransportRF69.h @@ -1,8 +1,8 @@ -#ifndef MyRFDriverRF69_h -#define MyRFDriverRF69_h +#ifndef MyTransportRF69_h +#define MyTransportRF69_h #include "MyConfig.h" -#include "MyRFDriver.h" +#include "MyTransport.h" #include #include "utility/RFM69.h" #include @@ -25,10 +25,10 @@ #define FLASH_SS 8 // and FLASH SS on D8 #endif -class MyRFDriverRF69 : public MyRFDriver +class MyTransportRF69 : public MyTransport { public: - MyRFDriverRF69(); + MyTransportRF69(); void init(); void setAddress(uint8_t address); uint8_t getAddress(); diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index def707b..d7433e4 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -44,7 +44,7 @@ #include #include -#include +#include #include #include #include @@ -72,7 +72,7 @@ // NRFRF24L01 radio driver (set low transmit power by default) -MyRFDriverNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); // Message signing driver (none default) MySigningDriverNone signer; // Construct MySensors library diff --git a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h index fa5f1b6..d564ea6 100644 --- a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h @@ -1,7 +1,7 @@ #ifndef __GATEWAYUTIL_H__ #define __GATEWAYUTIL_H__ -#include +#include #ifdef ARDUINO diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index 706ca3c..979440c 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -57,7 +57,7 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway */ #include -#include +#include #include #include #include @@ -92,7 +92,7 @@ uint8_t TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You ////////////////////////////////////////////////////////////////// // NRFRF24L01 radio driver (set low transmit power by default) -MyRFDriverNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); // Message signing driver (none default) MySigningDriverNone signer; // Construct MySensors library diff --git a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino index 65f0fe7..3517ef9 100644 --- a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino +++ b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino @@ -2,7 +2,7 @@ // This example will remember lock state even after power failure. #include -#include +#include #include #include @@ -11,7 +11,7 @@ #define LOCK_LOCK 1 // GPIO value to write to lock attached lock #define LOCK_UNLOCK 0 // GPIO value to write to unlock attached lock -MyRFDriverNRF24 radio; // NRFRF24L01 radio driver +MyTransportNRF24 radio; // NRFRF24L01 radio driver MySigningDriverAtsha204Soft signer; // Message signing driver MySensor gw(radio, signer); diff --git a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h index fa5f1b6..d564ea6 100644 --- a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h @@ -1,7 +1,7 @@ #ifndef __GATEWAYUTIL_H__ #define __GATEWAYUTIL_H__ -#include +#include #ifdef ARDUINO diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index c178b19..d300793 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -24,7 +24,7 @@ #define NO_PORTB_PINCHANGES #include -#include +#include #include #include #include @@ -41,7 +41,7 @@ // NRFRF24L01 radio driver (set low transmit power by default) -MyRFDriverNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); // Message signing driver (none default) MySigningDriverNone signer; // Construct MySensors library From 6d0ae813c4220c28ac43c5b843f3f6c37aec31c5 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 10 Mar 2015 00:07:57 +0100 Subject: [PATCH 069/137] Rename MySigningDriver* to MySigning* --- libraries/MySensors/MyConfig.h | 6 +++--- libraries/MySensors/MySensor.cpp | 2 +- libraries/MySensors/MySensor.h | 8 ++++---- libraries/MySensors/MySigning.cpp | 9 +++++++++ .../{MySigningDriver.h => MySigning.h} | 10 +++++----- ...iverAtsha204.cpp => MySigningAtsha204.cpp} | 20 +++++++++---------- ...ngDriverAtsha204.h => MySigningAtsha204.h} | 10 +++++----- ...a204Soft.cpp => MySigningAtsha204Soft.cpp} | 20 +++++++++---------- ...Atsha204Soft.h => MySigningAtsha204Soft.h} | 10 +++++----- libraries/MySensors/MySigningDriver.cpp | 9 --------- ...igningDriverNone.cpp => MySigningNone.cpp} | 16 +++++++-------- ...{MySigningDriverNone.h => MySigningNone.h} | 10 +++++----- .../EthernetGateway/EthernetGateway.ino | 4 ++-- .../examples/MQTTGateway/MQTTGateway.ino | 4 ++-- .../SecureActuator/SecureActuator.ino | 4 ++-- .../examples/SerialGateway/SerialGateway.ino | 4 ++-- 16 files changed, 73 insertions(+), 73 deletions(-) create mode 100644 libraries/MySensors/MySigning.cpp rename libraries/MySensors/{MySigningDriver.h => MySigning.h} (95%) rename libraries/MySensors/{MySigningDriverAtsha204.cpp => MySigningAtsha204.cpp} (93%) rename libraries/MySensors/{MySigningDriverAtsha204.h => MySigningAtsha204.h} (80%) rename libraries/MySensors/{MySigningDriverAtsha204Soft.cpp => MySigningAtsha204Soft.cpp} (92%) rename libraries/MySensors/{MySigningDriverAtsha204Soft.h => MySigningAtsha204Soft.h} (85%) delete mode 100644 libraries/MySensors/MySigningDriver.cpp rename libraries/MySensors/{MySigningDriverNone.cpp => MySigningNone.cpp} (77%) rename libraries/MySensors/{MySigningDriverNone.h => MySigningNone.h} (81%) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index b259a1c..9898fab 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -15,12 +15,12 @@ // which might vary, especially in networks with many hops. 5s ought to be enough for anyone. #define MY_VERIFICATION_TIMEOUT_MS 5000 -// MySigningDriverAtsha204 default setting +// MySigningAtsha204 default setting #define MY_ATSHA204_PIN 17 // A3 - pin where ATSHA204 is attached -// MySigningDriverAtsha204Soft default settings +// MySigningAtsha204Soft default settings #define MY_RANDOMSEED_PIN 7 // A7 - Pin used for random generation (do not connect anything to this) -// Key to use for HMAC calculation in MySigningDriverAtsha204Soft (32 bytes) +// Key to use for HMAC calculation in MySigningAtsha204Soft (32 bytes) #define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index e34b22f..c558e43 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -37,7 +37,7 @@ static inline bool isValidDistance( const uint8_t distance ) { return distance != DISTANCE_INVALID; } -MySensor::MySensor(MyTransport &_radio, MySigningDriver &_signer) +MySensor::MySensor(MyTransport &_radio, MySigning &_signer) : radio(_radio), signer(_signer) diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index b3a451d..f9d75bb 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -16,8 +16,8 @@ #include "MyTransport.h" #include "MyTransportNRF24.h" #include "MyParser.h" -#include "MySigningDriver.h" -#include "MySigningDriverNone.h" +#include "MySigning.h" +#include "MySigningNone.h" #include "MyConfig.h" #include "MyMessage.h" #include @@ -81,7 +81,7 @@ class MySensor * Creates a new instance of Sensor class. * */ - MySensor(MyTransport &radio =*new MyTransportNRF24(), MySigningDriver &signer=*new MySigningDriverNone()); + MySensor(MyTransport &radio =*new MyTransportNRF24(), MySigning &signer=*new MySigningNone()); /** * Begin operation of the MySensors library @@ -250,7 +250,7 @@ class MySensor MyMessage msgSign; // Buffer for message to sign. MyTransport& radio; - MySigningDriver& signer; + MySigning& signer; void setupRepeaterMode(); boolean sendWrite(uint8_t dest, MyMessage &message); diff --git a/libraries/MySensors/MySigning.cpp b/libraries/MySensors/MySigning.cpp new file mode 100644 index 0000000..835b947 --- /dev/null +++ b/libraries/MySensors/MySigning.cpp @@ -0,0 +1,9 @@ +#include "MySigning.h" + +MySigning::MySigning(bool requestSignatures) : _requestSignatures(requestSignatures) { +} + + +bool MySigning::requestSignatures() { + return _requestSignatures; +} diff --git a/libraries/MySensors/MySigningDriver.h b/libraries/MySensors/MySigning.h similarity index 95% rename from libraries/MySensors/MySigningDriver.h rename to libraries/MySensors/MySigning.h index ebabde8..dc4407d 100644 --- a/libraries/MySensors/MySigningDriver.h +++ b/libraries/MySensors/MySigning.h @@ -4,20 +4,20 @@ Created by Patrick "Anticimex" Fallberg */ -#ifndef MySigningDriver_h -#define MySigningDriver_h +#ifndef MySigning_h +#define MySigning_h #include #include "MyMessage.h" -class MySigningDriver +class MySigning { public: - // MySigningDriver constructor. + // MySigning constructor. // Different parameters would be needed depending on signing backend (e.g. pins connected etc.). // Keeping these parameters as #define's in MyConfig to streamline the driver interface. // @param requestSignatures Set this to true if you want destination node to sign all messages sent to this node. Default is not to require signing. - MySigningDriver(bool requestSignatures=false); + MySigning(bool requestSignatures=false); // Returns the current requestSignature setting bool requestSignatures(); diff --git a/libraries/MySensors/MySigningDriverAtsha204.cpp b/libraries/MySensors/MySigningAtsha204.cpp similarity index 93% rename from libraries/MySensors/MySigningDriverAtsha204.cpp rename to libraries/MySensors/MySigningAtsha204.cpp index 401a82c..1effefc 100644 --- a/libraries/MySensors/MySigningDriverAtsha204.cpp +++ b/libraries/MySensors/MySigningAtsha204.cpp @@ -4,8 +4,8 @@ Created by Patrick "Anticimex" Fallberg */ -#include "MySigningDriver.h" -#include "MySigningDriverAtsha204.h" +#include "MySigning.h" +#include "MySigningAtsha204.h" // Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) //#define DEBUG_ATSHA_SIGNING @@ -36,9 +36,9 @@ static void DEBUG_ATSHA_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) #endif -MySigningDriverAtsha204::MySigningDriverAtsha204(bool requestSignatures, uint8_t atshaPin) +MySigningAtsha204::MySigningAtsha204(bool requestSignatures, uint8_t atshaPin) : - MySigningDriver(requestSignatures), + MySigning(requestSignatures), atsha204(atshaPin), verification_ongoing(false) { @@ -46,7 +46,7 @@ MySigningDriverAtsha204::MySigningDriverAtsha204(bool requestSignatures, uint8_t memset(current_nonce, 0xAA, sizeof(current_nonce)); } -bool MySigningDriverAtsha204::getNonce(MyMessage &msg) { +bool MySigningAtsha204::getNonce(MyMessage &msg) { // Wake device before starting operations if (atsha204.sha204c_wakeup(rx_buffer) != SHA204_SUCCESS) { DEBUG_ATSHA_PRINTLN("Failed to wake device"); @@ -78,7 +78,7 @@ bool MySigningDriverAtsha204::getNonce(MyMessage &msg) { return true; } -bool MySigningDriverAtsha204::checkTimer() { +bool MySigningAtsha204::checkTimer() { if (verification_ongoing) { if (millis() < timestamp || millis() > timestamp + MY_VERIFICATION_TIMEOUT_MS) { DEBUG_ATSHA_PRINTLN("Verification timeout"); @@ -91,7 +91,7 @@ bool MySigningDriverAtsha204::checkTimer() { return true; } -bool MySigningDriverAtsha204::putNonce(MyMessage &msg) { +bool MySigningAtsha204::putNonce(MyMessage &msg) { if (mGetLength(msg) != MAX_PAYLOAD) { DEBUG_ATSHA_PRINTLN("Incoming nonce with incorrect size"); return false; // We require as big nonce as possible @@ -106,7 +106,7 @@ bool MySigningDriverAtsha204::putNonce(MyMessage &msg) { return true; } -bool MySigningDriverAtsha204::signMsg(MyMessage &msg) { +bool MySigningAtsha204::signMsg(MyMessage &msg) { // If we cannot fit any signature in the message, refuse to sign it if (mGetLength(msg) > MAX_PAYLOAD-2) { DEBUG_ATSHA_PRINTLN("Cannot fit any signature to this message"); @@ -128,7 +128,7 @@ bool MySigningDriverAtsha204::signMsg(MyMessage &msg) { return true; } -bool MySigningDriverAtsha204::verifyMsg(MyMessage &msg) { +bool MySigningAtsha204::verifyMsg(MyMessage &msg) { if (!verification_ongoing) { DEBUG_ATSHA_PRINTLN("No active verification session"); return false; @@ -166,7 +166,7 @@ bool MySigningDriverAtsha204::verifyMsg(MyMessage &msg) { } // Helper to calculate signature of msg (returned in rx_buffer[SHA204_BUFFER_POS_DATA]) -bool MySigningDriverAtsha204::calculateSignature(MyMessage &msg) { +bool MySigningAtsha204::calculateSignature(MyMessage &msg) { memset(temp_message, 0, 32); memcpy(temp_message, (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); diff --git a/libraries/MySensors/MySigningDriverAtsha204.h b/libraries/MySensors/MySigningAtsha204.h similarity index 80% rename from libraries/MySensors/MySigningDriverAtsha204.h rename to libraries/MySensors/MySigningAtsha204.h index 8da91ae..8850b2c 100644 --- a/libraries/MySensors/MySigningDriverAtsha204.h +++ b/libraries/MySensors/MySigningAtsha204.h @@ -4,11 +4,11 @@ Created by Patrick "Anticimex" Fallberg */ -#ifndef MySigningDriverAtsha204_h -#define MySigningDriverAtsha204_h +#ifndef MySigningAtsha204_h +#define MySigningAtsha204_h #include "MyConfig.h" -#include "MySigningDriver.h" +#include "MySigning.h" #include "utility/ATSHA204.h" #include @@ -17,10 +17,10 @@ // The ATSHA204 is capable of generating proper random numbers for nonce // and can calculate HMAC-SHA256 signatures. This is enterprise- // level of security and ought to implement the signing needs for anybody. -class MySigningDriverAtsha204 : public MySigningDriver +class MySigningAtsha204 : public MySigning { public: - MySigningDriverAtsha204(bool requestSignatures=true, uint8_t atshaPin = MY_ATSHA204_PIN); + MySigningAtsha204(bool requestSignatures=true, uint8_t atshaPin = MY_ATSHA204_PIN); bool getNonce(MyMessage &msg); bool checkTimer(void); bool putNonce(MyMessage &msg); diff --git a/libraries/MySensors/MySigningDriverAtsha204Soft.cpp b/libraries/MySensors/MySigningAtsha204Soft.cpp similarity index 92% rename from libraries/MySensors/MySigningDriverAtsha204Soft.cpp rename to libraries/MySensors/MySigningAtsha204Soft.cpp index c9f6e44..3ac6f38 100644 --- a/libraries/MySensors/MySigningDriverAtsha204Soft.cpp +++ b/libraries/MySensors/MySigningAtsha204Soft.cpp @@ -8,8 +8,8 @@ Created by Patrick "Anticimex" Fallberg */ #include "MyConfig.h" -#include "MySigningDriver.h" -#include "MySigningDriverAtsha204Soft.h" +#include "MySigning.h" +#include "MySigningAtsha204Soft.h" #include "utility/sha256.h" // Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) @@ -40,9 +40,9 @@ static void DEBUG_ATSHASOFT_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) #define DEBUG_ATSHASOFT_PRINTBUF(str, buf, sz) #endif -MySigningDriverAtsha204Soft::MySigningDriverAtsha204Soft(bool requestSignatures, uint8_t randomseedPin) +MySigningAtsha204Soft::MySigningAtsha204Soft(bool requestSignatures, uint8_t randomseedPin) : - MySigningDriver(requestSignatures), + MySigning(requestSignatures), rndPin(randomseedPin), hmacKey({MY_HMAC_KEY}), verification_ongoing(false), @@ -53,7 +53,7 @@ MySigningDriverAtsha204Soft::MySigningDriverAtsha204Soft(bool requestSignatures, memset(current_nonce, 0xAA, sizeof(current_nonce)); } -bool MySigningDriverAtsha204Soft::getNonce(MyMessage &msg) { +bool MySigningAtsha204Soft::getNonce(MyMessage &msg) { // Set randomseed randomSeed(analogRead(rndPin)); for (int i = 0; i < MAX_PAYLOAD; i++) @@ -73,7 +73,7 @@ bool MySigningDriverAtsha204Soft::getNonce(MyMessage &msg) { return true; } -bool MySigningDriverAtsha204Soft::checkTimer() { +bool MySigningAtsha204Soft::checkTimer() { if (verification_ongoing) { if (millis() < timestamp || millis() > timestamp + MY_VERIFICATION_TIMEOUT_MS) { DEBUG_ATSHASOFT_PRINTLN("Verification timeout"); @@ -86,7 +86,7 @@ bool MySigningDriverAtsha204Soft::checkTimer() { return true; } -bool MySigningDriverAtsha204Soft::putNonce(MyMessage &msg) { +bool MySigningAtsha204Soft::putNonce(MyMessage &msg) { if (mGetLength(msg) != MAX_PAYLOAD) { DEBUG_ATSHASOFT_PRINTLN("Incoming nonce with incorrect size"); return false; // We require as big nonce as possible @@ -101,7 +101,7 @@ bool MySigningDriverAtsha204Soft::putNonce(MyMessage &msg) { return true; } -bool MySigningDriverAtsha204Soft::signMsg(MyMessage &msg) { +bool MySigningAtsha204Soft::signMsg(MyMessage &msg) { // If we cannot fit any signature in the message, refuse to sign it if (mGetLength(msg) > MAX_PAYLOAD-2) { DEBUG_ATSHASOFT_PRINTLN("Cannot fit any signature to this message"); @@ -123,7 +123,7 @@ bool MySigningDriverAtsha204Soft::signMsg(MyMessage &msg) { return true; } -bool MySigningDriverAtsha204Soft::verifyMsg(MyMessage &msg) { +bool MySigningAtsha204Soft::verifyMsg(MyMessage &msg) { if (!verification_ongoing) { DEBUG_ATSHASOFT_PRINTLN("No active verification session"); return false; @@ -161,7 +161,7 @@ bool MySigningDriverAtsha204Soft::verifyMsg(MyMessage &msg) { } // Helper to calculate signature of msg (returned in rx_buffer[SHA204_BUFFER_POS_DATA]) -bool MySigningDriverAtsha204Soft::calculateSignature(MyMessage &msg) { +bool MySigningAtsha204Soft::calculateSignature(MyMessage &msg) { memset(temp_message, 0, 32); memcpy(temp_message, (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); diff --git a/libraries/MySensors/MySigningDriverAtsha204Soft.h b/libraries/MySensors/MySigningAtsha204Soft.h similarity index 85% rename from libraries/MySensors/MySigningDriverAtsha204Soft.h rename to libraries/MySensors/MySigningAtsha204Soft.h index eef0a31..daf954d 100644 --- a/libraries/MySensors/MySigningDriverAtsha204Soft.h +++ b/libraries/MySensors/MySigningAtsha204Soft.h @@ -7,11 +7,11 @@ Created by Patrick "Anticimex" Fallberg */ -#ifndef MySigningDriverHmac256Soft_h -#define MySigningDriverHmac256Soft_h +#ifndef MySigningHmac256Soft_h +#define MySigningHmac256Soft_h #include "MyConfig.h" -#include "MySigningDriver.h" +#include "MySigning.h" #include "utility/ATSHA204.h" #include "utility/sha256.h" #include @@ -25,10 +25,10 @@ // is weaker though. Random numbers are generated using the Arduino library and seed // is sampled from an analog pin. This pin should unconnected in the hardware. // The pin is selected using MY_RANDOMSEED_PIN in MyConfig.h. -class MySigningDriverAtsha204Soft : public MySigningDriver +class MySigningAtsha204Soft : public MySigning { public: - MySigningDriverAtsha204Soft(bool requestSignatures=true, uint8_t randomseedPin = MY_RANDOMSEED_PIN); + MySigningAtsha204Soft(bool requestSignatures=true, uint8_t randomseedPin = MY_RANDOMSEED_PIN); bool getNonce(MyMessage &msg); bool checkTimer(void); bool putNonce(MyMessage &msg); diff --git a/libraries/MySensors/MySigningDriver.cpp b/libraries/MySensors/MySigningDriver.cpp deleted file mode 100644 index aa718fc..0000000 --- a/libraries/MySensors/MySigningDriver.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "MySigningDriver.h" - -MySigningDriver::MySigningDriver(bool requestSignatures) : _requestSignatures(requestSignatures) { -} - - -bool MySigningDriver::requestSignatures() { - return _requestSignatures; -} diff --git a/libraries/MySensors/MySigningDriverNone.cpp b/libraries/MySensors/MySigningNone.cpp similarity index 77% rename from libraries/MySensors/MySigningDriverNone.cpp rename to libraries/MySensors/MySigningNone.cpp index a7ace62..e15f724 100644 --- a/libraries/MySensors/MySigningDriverNone.cpp +++ b/libraries/MySensors/MySigningNone.cpp @@ -3,8 +3,8 @@ Created by Patrick "Anticimex" Fallberg */ -#include "MySigningDriver.h" -#include "MySigningDriverNone.h" +#include "MySigning.h" +#include "MySigningNone.h" // Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) //#define DEBUG_NONE_SIGNING @@ -34,22 +34,22 @@ static void DEBUG_NONE_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) #define DEBUG_NONE_PRINTBUF(str, buf, sz) #endif -MySigningDriverNone::MySigningDriverNone() : MySigningDriver() { +MySigningNone::MySigningNone() : MySigning() { } -bool MySigningDriverNone::getNonce(MyMessage &msg) { +bool MySigningNone::getNonce(MyMessage &msg) { return true; } -bool MySigningDriverNone::checkTimer() { +bool MySigningNone::checkTimer() { return true; } -bool MySigningDriverNone::putNonce(MyMessage &msg) { +bool MySigningNone::putNonce(MyMessage &msg) { return true; } -bool MySigningDriverNone::signMsg(MyMessage &msg) { +bool MySigningNone::signMsg(MyMessage &msg) { // If we cannot fit any signature in the message, refuse to sign it if (mGetLength(msg) > MAX_PAYLOAD-2) { DEBUG_NONE_PRINTLN("Cannot fit any signature to this message"); @@ -60,7 +60,7 @@ bool MySigningDriverNone::signMsg(MyMessage &msg) { return true; } -bool MySigningDriverNone::verifyMsg(MyMessage &msg) { +bool MySigningNone::verifyMsg(MyMessage &msg) { if (msg.data[mGetLength(msg)] != SIGNING_IDENTIFIER) return false; else diff --git a/libraries/MySensors/MySigningDriverNone.h b/libraries/MySensors/MySigningNone.h similarity index 81% rename from libraries/MySensors/MySigningDriverNone.h rename to libraries/MySensors/MySigningNone.h index 9718a78..dd8f319 100644 --- a/libraries/MySensors/MySigningDriverNone.h +++ b/libraries/MySensors/MySigningNone.h @@ -3,11 +3,11 @@ Created by Patrick "Anticimex" Fallberg */ -#ifndef MySigningDriverNone_h -#define MySigningDriverNone_h +#ifndef MySigningNone_h +#define MySigningNone_h #include "MyConfig.h" -#include "MySigningDriver.h" +#include "MySigning.h" #include #define SIGNING_IDENTIFIER (0) @@ -17,10 +17,10 @@ // It does check SIGNING_IDENTIFIER byte to avoid illegal mixing of signing back-ends in // the network (as seen by this node) and it does verify proper execution order on the API. // The "none" driver rejects all other back-ends. -class MySigningDriverNone : public MySigningDriver +class MySigningNone : public MySigning { public: - MySigningDriverNone(); + MySigningNone(); bool getNonce(MyMessage &msg); bool checkTimer(void); bool putNonce(MyMessage &msg); diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index d7433e4..bde2cf1 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -43,7 +43,7 @@ #include // This include can be removed when using UIPEthernet module #include -#include +#include #include #include #include @@ -74,7 +74,7 @@ // NRFRF24L01 radio driver (set low transmit power by default) MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); // Message signing driver (none default) -MySigningDriverNone signer; +MySigningNone signer; // Construct MySensors library MySensor gw(radio, signer); diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index 979440c..bb1ea20 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -56,7 +56,7 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway */ -#include +#include #include #include #include @@ -94,7 +94,7 @@ uint8_t TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You // NRFRF24L01 radio driver (set low transmit power by default) MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); // Message signing driver (none default) -MySigningDriverNone signer; +MySigningNone signer; // Construct MySensors library MySensor gw(radio, signer); diff --git a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino index 3517ef9..d249f29 100644 --- a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino +++ b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino @@ -1,7 +1,7 @@ // Example sketch showing how to securely control locks. // This example will remember lock state even after power failure. -#include +#include #include #include #include @@ -12,7 +12,7 @@ #define LOCK_UNLOCK 0 // GPIO value to write to unlock attached lock MyTransportNRF24 radio; // NRFRF24L01 radio driver -MySigningDriverAtsha204Soft signer; // Message signing driver +MySigningAtsha204Soft signer; // Message signing driver MySensor gw(radio, signer); void setup() diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index d300793..8dc5e26 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -23,7 +23,7 @@ #define NO_PORTB_PINCHANGES -#include +#include #include #include #include @@ -43,7 +43,7 @@ // NRFRF24L01 radio driver (set low transmit power by default) MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); // Message signing driver (none default) -MySigningDriverNone signer; +MySigningNone signer; // Construct MySensors library MySensor gw(radio, signer); From 9e85fac74546456552d38b9feeeaaa7c710bf4b3 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 12 Mar 2015 22:59:51 +0100 Subject: [PATCH 070/137] Separate the HW specifics from the MySensor library --- libraries/MySensors/MyConfig.h | 2 + libraries/MySensors/MyHw.cpp | 4 + libraries/MySensors/MyHw.h | 35 +++ libraries/MySensors/MyHwATMega328.cpp | 141 ++++++++++++ libraries/MySensors/MyHwATMega328.h | 40 ++++ libraries/MySensors/MySensor.cpp | 206 +++++------------- libraries/MySensors/MySensor.h | 38 ++-- libraries/MySensors/MyTransport.h | 2 +- .../ClearEepromConfig/ClearEepromConfig.ino | 4 + .../examples/RelayActuator/RelayActuator.ino | 12 +- 10 files changed, 308 insertions(+), 176 deletions(-) create mode 100644 libraries/MySensors/MyHw.cpp create mode 100644 libraries/MySensors/MyHw.h create mode 100644 libraries/MySensors/MyHwATMega328.cpp create mode 100644 libraries/MySensors/MyHwATMega328.h diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 9898fab..3e09981 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -6,6 +6,8 @@ ***********************************/ #define DEBUG +#define BAUD_RATE 115200 + /********************************** * Message Signing Settings diff --git a/libraries/MySensors/MyHw.cpp b/libraries/MySensors/MyHw.cpp new file mode 100644 index 0000000..75f020d --- /dev/null +++ b/libraries/MySensors/MyHw.cpp @@ -0,0 +1,4 @@ +#include "MyHw.h" + +MyHw::MyHw() { +} diff --git a/libraries/MySensors/MyHw.h b/libraries/MySensors/MyHw.h new file mode 100644 index 0000000..a7ce870 --- /dev/null +++ b/libraries/MySensors/MyHw.h @@ -0,0 +1,35 @@ +#ifndef MyHw_h +#define MyHw_h + +#include +#include +#include "MyConfig.h" + +//#include "MySensor.h" +/** + * The Hw contains all hardware specific details of the platform + */ + +class MyHw +{ +public: + // MyHw constructor + MyHw(); + virtual void init() = 0; + virtual void watchdogReset() = 0; + virtual void reboot() = 0; + virtual unsigned long millisec() = 0; + virtual void sleep(unsigned long ms) = 0; + virtual bool sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) = 0; + virtual uint8_t sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) = 0; + virtual uint8_t readConfigByte(uint8_t pos) = 0; + virtual void writeConfigByte(uint8_t pos, uint8_t value) = 0; + virtual void readConfigBlock(void* buf, void * pos, size_t length) = 0; + virtual void writeConfigBlock(void* pos, void* buf, uint16_t length) = 0; + #ifdef DEBUG + virtual void debugPrint(bool isGW, const char *fmt, ... ) = 0; + #endif + +}; + +#endif diff --git a/libraries/MySensors/MyHwATMega328.cpp b/libraries/MySensors/MyHwATMega328.cpp new file mode 100644 index 0000000..3f42fc9 --- /dev/null +++ b/libraries/MySensors/MyHwATMega328.cpp @@ -0,0 +1,141 @@ +#include "MyHw.h" +#include "MyHwATMega328.h" + +int8_t pinIntTrigger = 0; +void wakeUp() //place to send the interrupts +{ + pinIntTrigger = 1; +} +void wakeUp2() //place to send the second interrupts +{ + pinIntTrigger = 2; +} + +MyHwATMega328::MyHwATMega328() : MyHw() +{ +} + + +void MyHwATMega328::init() { + Serial.begin(BAUD_RATE); +} + +void MyHwATMega328::watchdogReset() { + wdt_reset(); +} + +void MyHwATMega328::reboot() { + wdt_enable(WDTO_15MS); + for (;;); +} + +unsigned long MyHwATMega328::millisec() { + return millis(); +} + + +void MyHwATMega328::sleep(unsigned long ms) { + // Let serial prints finish (debug, log etc) + Serial.flush(); + pinIntTrigger = 0; + while (!pinIntTrigger && ms >= 8000) { LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); ms -= 8000; } + if (!pinIntTrigger && ms >= 4000) { LowPower.powerDown(SLEEP_4S, ADC_OFF, BOD_OFF); ms -= 4000; } + if (!pinIntTrigger && ms >= 2000) { LowPower.powerDown(SLEEP_2S, ADC_OFF, BOD_OFF); ms -= 2000; } + if (!pinIntTrigger && ms >= 1000) { LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF); ms -= 1000; } + if (!pinIntTrigger && ms >= 500) { LowPower.powerDown(SLEEP_500MS, ADC_OFF, BOD_OFF); ms -= 500; } + if (!pinIntTrigger && ms >= 250) { LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF); ms -= 250; } + if (!pinIntTrigger && ms >= 125) { LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_OFF); ms -= 120; } + if (!pinIntTrigger && ms >= 64) { LowPower.powerDown(SLEEP_60MS, ADC_OFF, BOD_OFF); ms -= 60; } + if (!pinIntTrigger && ms >= 32) { LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF); ms -= 30; } + if (!pinIntTrigger && ms >= 16) { LowPower.powerDown(SLEEP_15Ms, ADC_OFF, BOD_OFF); ms -= 15; } +} + +bool MyHwATMega328::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { + // Let serial prints finish (debug, log etc) + bool pinTriggeredWakeup = true; + Serial.flush(); + attachInterrupt(interrupt, wakeUp, mode); + if (ms>0) { + pinIntTrigger = 0; + sleep(ms); + if (0 == pinIntTrigger) { + pinTriggeredWakeup = false; + } + } else { + Serial.flush(); + LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); + } + detachInterrupt(interrupt); + return pinTriggeredWakeup; +} + +uint8_t MyHwATMega328::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) { + int8_t retVal = 1; + Serial.flush(); // Let serial prints finish (debug, log etc) + attachInterrupt(interrupt1, wakeUp, mode1); + attachInterrupt(interrupt2, wakeUp2, mode2); + if (ms>0) { + pinIntTrigger = 0; + sleep(ms); + if (0 == pinIntTrigger) { + retVal = -1; + } + } else { + Serial.flush(); + LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); + } + detachInterrupt(interrupt1); + detachInterrupt(interrupt2); + + if (1 == pinIntTrigger) { + retVal = (int8_t)interrupt1; + } else if (2 == pinIntTrigger) { + retVal = (int8_t)interrupt2; + } + return retVal; +} + +uint8_t MyHwATMega328::readConfigByte(uint8_t pos) { + return eeprom_read_byte((uint8_t*)pos); +} + +void MyHwATMega328::writeConfigByte(uint8_t pos, uint8_t value) { + eeprom_update_byte((uint8_t*)pos, value); +} + +void MyHwATMega328::readConfigBlock(void* buf, void * pos, size_t length) { + eeprom_read_block(buf, (void*)pos, length); +} + +void MyHwATMega328::writeConfigBlock(void* pos, void* buf, size_t length) { + eeprom_write_block((void*)pos, (void*)buf, length); +} + + +#ifdef DEBUG +void MyHwATMega328::debugPrint(bool isGW, const char *fmt, ... ) { + char fmtBuffer[300]; + if (isGW) { + // prepend debug message to be handled correctly by controller (C_INTERNAL, I_LOG_MESSAGE) + snprintf_P(fmtBuffer, 299, PSTR("0;0;%d;0;%d;"), C_INTERNAL, I_LOG_MESSAGE); + Serial.print(fmtBuffer); + } + va_list args; + va_start (args, fmt ); + va_end (args); + if (isGW) { + // Truncate message if this is gateway node + vsnprintf_P(fmtBuffer, 60, fmt, args); + fmtBuffer[59] = '\n'; + fmtBuffer[60] = '\0'; + } else { + vsnprintf_P(fmtBuffer, 299, fmt, args); + } + va_end (args); + Serial.print(fmtBuffer); + Serial.flush(); + + //Serial.write(freeRam()); +} +#endif + diff --git a/libraries/MySensors/MyHwATMega328.h b/libraries/MySensors/MyHwATMega328.h new file mode 100644 index 0000000..90e6e82 --- /dev/null +++ b/libraries/MySensors/MyHwATMega328.h @@ -0,0 +1,40 @@ +#ifndef MyHwATMega328_h +#define MyHwATMega328_h + +#include "MyConfig.h" +#include "MyMessage.h" +#include +#include +#include +#include "utility/LowPower.h" + +#include "MyHw.h" + +#ifdef __cplusplus +#include +#include +#endif + + +class MyHwATMega328 : public MyHw +{ +public: + MyHwATMega328(); + + void init(); + void watchdogReset(); + void reboot(); + unsigned long millisec(); + void sleep(unsigned long ms); + bool sleep(uint8_t interrupt, uint8_t mode, unsigned long ms); + uint8_t sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms); + uint8_t readConfigByte(uint8_t pos); + void writeConfigByte(uint8_t pos, uint8_t value); + void readConfigBlock(void* buf, void * pos, size_t length); + void writeConfigBlock(void* pos, void* buf, size_t length); +#ifdef DEBUG + void debugPrint(bool isGW, const char *fmt, ... ); +#endif +private: +}; +#endif diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index c558e43..bb69787 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -37,16 +37,17 @@ static inline bool isValidDistance( const uint8_t distance ) { return distance != DISTANCE_INVALID; } -MySensor::MySensor(MyTransport &_radio, MySigning &_signer) +MySensor::MySensor(MyTransport &_radio, MySigning &_signer, MyHw &_hw) : radio(_radio), - signer(_signer) + signer(_signer), + hw(_hw) { } void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId) { - Serial.begin(BAUD_RATE); + hw.init(); repeaterMode = _repeaterMode; msgCallback = _msgCallback; failedTransmissions = 0; @@ -62,11 +63,11 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b radio.init(); // Read settings from eeprom - eeprom_read_block((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); + hw.readConfigBlock((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); // Read latest received controller configuration from EEPROM - eeprom_read_block((void*)&cc, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS, sizeof(ControllerConfig)); + hw.readConfigBlock((void*)&cc, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS, sizeof(ControllerConfig)); // Read out the signing requirements from EEPROM - eeprom_read_block((void*)doSign, (void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, sizeof(doSign)); + hw.readConfigBlock((void*)doSign, (void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, sizeof(doSign)); if (isGateway) { nc.distance = 0; @@ -81,7 +82,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b if (!autoFindParent) { nc.parentNodeId = _parentNodeId; // Save static parent id in eeprom (used by bootloader) - eeprom_update_byte((uint8_t*)EEPROM_PARENT_NODE_ID_ADDRESS, _parentNodeId); + hw.writeConfigByte(EEPROM_PARENT_NODE_ID_ADDRESS, _parentNodeId); // We don't actually know the distance to gw here. Let's pretend it is 1. // If the current node is also repeater, be aware of this. nc.distance = 1; @@ -90,24 +91,26 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b findParentNode(); } - if (_nodeId != AUTO) { - // Set static id - nc.nodeId = _nodeId; - // Save static id in eeprom - eeprom_update_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, _nodeId); - } else if (isValidParent(nc.parentNodeId)) { - // Try to fetch node-id from gateway - requestNodeId(); + if (!isGateway) { + if (_nodeId != AUTO) { + // Set static id + nc.nodeId = _nodeId; + // Save static id in eeprom + if (_nodeId > 0) + hw.writeConfigByte(EEPROM_NODE_ID_ADDRESS, _nodeId); + } else if (isValidParent(nc.parentNodeId)) { + // Try to fetch node-id from gateway + requestNodeId(); + } } setupNode(); - debug(PSTR("%s started, id=%d, parent=%d, distance=%d\n"), isGateway?"gateway":(repeaterMode?"repeater":"sensor"), nc.nodeId, nc.parentNodeId, nc.distance); } void MySensor::setupRepeaterMode(){ // childNodeTable = new uint8_t[256]; - eeprom_read_block((void*)childNodeTable, (void*)EEPROM_ROUTES_ADDRESS, 256); + hw.readConfigBlock((void*)childNodeTable, (void *)EEPROM_ROUTES_ADDRESS, 256); } uint8_t MySensor::getNodeId() { @@ -119,7 +122,7 @@ ControllerConfig MySensor::getConfig() { } void MySensor::requestNodeId() { - debug(PSTR("req node id\n")); + debug(PSTR("req id\n")); radio.setAddress(nc.nodeId); build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_ID_REQUEST, false).set(""); sendWrite(nc.parentNodeId, msg); @@ -135,7 +138,7 @@ void MySensor::setupNode() { // Notify gateway (and possibly controller) about the signing preferences of this node sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(signer.requestSignatures())); - // If we do require signing, wait for the gateway to tell us how it perfer us to transmit our messages + // If we do require signing, wait for the gateway to tell us how it prefer us to transmit our messages if (signer.requestSignatures()) { wait(2000); } @@ -197,7 +200,7 @@ boolean MySensor::sendRoute(MyMessage &message) { message.type != I_ID_REQUEST && message.type != I_ID_RESPONSE && message.type != I_FIND_PARENT && message.type != I_FIND_PARENT_RESPONSE))) { if (!sign(message)) { - debug(PSTR("Message signing failed\n")); + debug(PSTR("sign fail\n")); return false; } // After this point, only the 'last' member of the message structure is allowed to be altered if the message has been signed, @@ -312,6 +315,7 @@ void MySensor::requestTime(void (* _timeCallback)(unsigned long)) { } boolean MySensor::process() { + hw.watchdogReset(); uint8_t to = 0; if (!radio.available(&to)) return false; @@ -328,11 +332,12 @@ boolean MySensor::process() { msg.type != I_ID_REQUEST && msg.type != I_ID_RESPONSE && msg.type != I_FIND_PARENT && msg.type != I_FIND_PARENT_RESPONSE))) { if (!mGetSigned(msg)) { - debug(PSTR("Got unsigned message that should have been signed\n")); + // Got unsigned message that should have been signed + debug(PSTR("no sign\n")); return false; } else if (!signer.verifyMsg(msg)) { - debug(PSTR("Message verification failed\n")); + debug(PSTR("verify fail\n")); return false; // This signed message has been tampered with! } } @@ -344,8 +349,7 @@ boolean MySensor::process() { mSetSigned(msg,0); // Clear the sign-flag now as verification (and debug printing) is completed if(!(mGetVersion(msg) == PROTOCOL_VERSION)) { - debug(PSTR("version: %d\n"),mGetVersion(msg)); - debug(PSTR("version mismatch\n")); + debug(PSTR("ver mismatch\n")); return false; } @@ -388,9 +392,9 @@ boolean MySensor::process() { // Found a neighbor closer to GW than previously found nc.distance = distance; nc.parentNodeId = msg.sender; - eeprom_update_byte((uint8_t*)EEPROM_PARENT_NODE_ID_ADDRESS, nc.parentNodeId); - eeprom_update_byte((uint8_t*)EEPROM_DISTANCE_ADDRESS, nc.distance); - debug(PSTR("new parent=%d, d=%d\n"), nc.parentNodeId, nc.distance); + hw.writeConfigByte(EEPROM_PARENT_NODE_ID_ADDRESS, nc.parentNodeId); + hw.writeConfigByte(EEPROM_DISTANCE_ADDRESS, nc.distance); + debug(PSTR("parent=%d, d=%d\n"), nc.parentNodeId, nc.distance); } } } @@ -409,7 +413,7 @@ boolean MySensor::process() { CLEAR_SIGN(msg.sender); } // Save updated table - eeprom_update_block((void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, (void*)doSign, sizeof(doSign)); + hw.writeConfigBlock((void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, (void*)doSign, sizeof(doSign)); // Inform sender about our preference if we are a gateway, but only require signing if the sender required signing // We do not currently want a gateway to require signing from all nodes in a network just because it wants one node @@ -428,8 +432,7 @@ boolean MySensor::process() { if (type == I_REBOOT) { // Requires MySensors or other bootloader with watchdogs enabled - wdt_enable(WDTO_15MS); - for (;;); + hw.reboot(); } else if (type == I_ID_RESPONSE) { if (nc.nodeId == AUTO) { nc.nodeId = msg.getByte(); @@ -440,7 +443,7 @@ boolean MySensor::process() { } setupNode(); // Write id to EEPROM - eeprom_update_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, nc.nodeId); + hw.writeConfigByte(EEPROM_NODE_ID_ADDRESS, nc.nodeId); debug(PSTR("id=%d\n"), nc.nodeId); } } else if (type == I_CONFIG) { @@ -448,18 +451,18 @@ boolean MySensor::process() { // and store it in eeprom if changed isMetric = msg.getString()[0] == 'M' ; cc.isMetric = isMetric; - eeprom_update_byte((uint8_t*)EEPROM_CONTROLLER_CONFIG_ADDRESS, isMetric); + hw.writeConfigByte(EEPROM_CONTROLLER_CONFIG_ADDRESS, isMetric); } else if (type == I_CHILDREN) { if (repeaterMode && msg.getString()[0] == 'C') { // Clears child relay data for this node - debug(PSTR("rd=clear\n")); + debug(PSTR("clear\n")); uint8_t i = 255; do { removeChildRoute(i); } while (i--); // Clear parent node id & distance to gw - eeprom_update_byte((uint8_t*)EEPROM_PARENT_NODE_ID_ADDRESS, 0xFF); - eeprom_update_byte((uint8_t*)EEPROM_DISTANCE_ADDRESS, 0xFF); + hw.writeConfigByte(EEPROM_PARENT_NODE_ID_ADDRESS, 0xFF); + hw.writeConfigByte(EEPROM_DISTANCE_ADDRESS, 0xFF); // Find parent node findParentNode(); sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_CHILDREN,false).set("")); @@ -484,7 +487,7 @@ boolean MySensor::process() { // Relaying nodes should always answer ping messages // Wait a random delay of 0-2 seconds to minimize collision // between ping ack messages from other relaying nodes - delay(millis() & 0x3ff); + wait(hw.millisec() & 0x3ff); sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance)); } } else if (to == nc.nodeId) { @@ -500,113 +503,48 @@ MyMessage& MySensor::getLastMessage() { } void MySensor::saveState(uint8_t pos, uint8_t value) { - eeprom_update_byte((uint8_t*)(EEPROM_LOCAL_CONFIG_ADDRESS+pos), value); + hw.writeConfigByte(EEPROM_LOCAL_CONFIG_ADDRESS+pos, value); } uint8_t MySensor::loadState(uint8_t pos) { - return eeprom_read_byte((uint8_t*)(EEPROM_LOCAL_CONFIG_ADDRESS+pos)); + return hw.readConfigByte(EEPROM_LOCAL_CONFIG_ADDRESS+pos); } void MySensor::addChildRoute(uint8_t childId, uint8_t route) { childNodeTable[childId] = route; - eeprom_update_byte((uint8_t*)EEPROM_ROUTES_ADDRESS+childId, route); + hw.writeConfigByte(EEPROM_ROUTES_ADDRESS+childId, route); } void MySensor::removeChildRoute(uint8_t childId) { childNodeTable[childId] = 0xff; - eeprom_update_byte((uint8_t*)EEPROM_ROUTES_ADDRESS+childId, 0xff); + hw.writeConfigByte(EEPROM_ROUTES_ADDRESS+childId, 0xff); } uint8_t MySensor::getChildRoute(uint8_t childId) { return childNodeTable[childId]; } -int8_t pinIntTrigger = 0; -void wakeUp() //place to send the interrupts -{ - pinIntTrigger = 1; -} -void wakeUp2() //place to send the second interrupts -{ - pinIntTrigger = 2; -} -void MySensor::internalSleep(unsigned long ms) { - while (!pinIntTrigger && ms >= 8000) { LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); ms -= 8000; } - if (!pinIntTrigger && ms >= 4000) { LowPower.powerDown(SLEEP_4S, ADC_OFF, BOD_OFF); ms -= 4000; } - if (!pinIntTrigger && ms >= 2000) { LowPower.powerDown(SLEEP_2S, ADC_OFF, BOD_OFF); ms -= 2000; } - if (!pinIntTrigger && ms >= 1000) { LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF); ms -= 1000; } - if (!pinIntTrigger && ms >= 500) { LowPower.powerDown(SLEEP_500MS, ADC_OFF, BOD_OFF); ms -= 500; } - if (!pinIntTrigger && ms >= 250) { LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF); ms -= 250; } - if (!pinIntTrigger && ms >= 125) { LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_OFF); ms -= 120; } - if (!pinIntTrigger && ms >= 64) { LowPower.powerDown(SLEEP_60MS, ADC_OFF, BOD_OFF); ms -= 60; } - if (!pinIntTrigger && ms >= 32) { LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF); ms -= 30; } - if (!pinIntTrigger && ms >= 16) { LowPower.powerDown(SLEEP_15Ms, ADC_OFF, BOD_OFF); ms -= 15; } -} - -void MySensor::sleep(unsigned long ms) { - // Let serial prints finish (debug, log etc) - Serial.flush(); - radio.powerDown(); - pinIntTrigger = 0; - internalSleep(ms); -} void MySensor::wait(unsigned long ms) { - // Let serial prints finish (debug, log etc) - Serial.flush(); - unsigned long enter = millis(); - while (millis() - enter < ms) { - // reset watchdog - wdt_reset(); + unsigned long enter = hw.millisec(); + while (hw.millisec() - enter < ms) { process(); } } -bool MySensor::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { - // Let serial prints finish (debug, log etc) - bool pinTriggeredWakeup = true; - Serial.flush(); +void MySensor::sleep(unsigned long ms) { radio.powerDown(); - attachInterrupt(interrupt, wakeUp, mode); - if (ms>0) { - pinIntTrigger = 0; - sleep(ms); - if (0 == pinIntTrigger) { - pinTriggeredWakeup = false; - } - } else { - Serial.flush(); - LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); - } - detachInterrupt(interrupt); - return pinTriggeredWakeup; + hw.sleep(ms); +} + +bool MySensor::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { + radio.powerDown(); + return hw.sleep(interrupt, mode, ms) ; } int8_t MySensor::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) { - int8_t retVal = 1; - Serial.flush(); // Let serial prints finish (debug, log etc) radio.powerDown(); - attachInterrupt(interrupt1, wakeUp, mode1); - attachInterrupt(interrupt2, wakeUp2, mode2); - if (ms>0) { - pinIntTrigger = 0; - sleep(ms); - if (0 == pinIntTrigger) { - retVal = -1; - } - } else { - Serial.flush(); - LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); - } - detachInterrupt(interrupt1); - detachInterrupt(interrupt2); - - if (1 == pinIntTrigger) { - retVal = (int8_t)interrupt1; - } else if (2 == pinIntTrigger) { - retVal = (int8_t)interrupt2; - } - return retVal; + return hw.sleep(interrupt1, mode1, interrupt2, mode2, ms) ; } bool MySensor::sign(MyMessage &message) { @@ -615,9 +553,9 @@ bool MySensor::sign(MyMessage &message) { } else { // We have to wait for the nonce to arrive before we can sign our original message // Other messages could come in-between. We trust process() takes care of them - unsigned long enter = millis(); + unsigned long enter = hw.millisec(); msgSign = message; // Copy the message to sign since message buffer might be touched in process() - while (millis() - enter < 5000) { + while (hw.millisec() - enter < 5000) { if (process()) { if (mGetCommand(getLastMessage()) == C_INTERNAL && getLastMessage().type == I_GET_NONCE_RESPONSE) { // Proceed with signing if nonce has been received @@ -633,37 +571,3 @@ bool MySensor::sign(MyMessage &message) { return false; } -#ifdef DEBUG -void MySensor::debugPrint(const char *fmt, ... ) { - char fmtBuffer[300]; - if (isGateway) { - // prepend debug message to be handled correctly by gw (C_INTERNAL, I_LOG_MESSAGE) - snprintf_P(fmtBuffer, 299, PSTR("0;0;%d;0;%d;"), C_INTERNAL, I_LOG_MESSAGE); - Serial.print(fmtBuffer); - } - va_list args; - va_start (args, fmt ); - va_end (args); - if (isGateway) { - // Truncate message if this is gateway node - vsnprintf_P(fmtBuffer, 60, fmt, args); - fmtBuffer[59] = '\n'; - fmtBuffer[60] = '\0'; - } else { - vsnprintf_P(fmtBuffer, 299, fmt, args); - } - va_end (args); - Serial.print(fmtBuffer); - Serial.flush(); - - //Serial.write(freeRam()); -} -#endif - -#ifdef DEBUG -int MySensor::freeRam (void) { - extern int __heap_start, *__brkval; - int v; - return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); -} -#endif diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index f9d75bb..5ccac1a 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -13,6 +13,8 @@ #define MySensor_h #include "Version.h" // Auto generated by bot +#include "MyHw.h" +#include "MyHwATMega328.h" #include "MyTransport.h" #include "MyTransportNRF24.h" #include "MyParser.h" @@ -21,24 +23,15 @@ #include "MyConfig.h" #include "MyMessage.h" #include -#include -#include -#include #include -#ifdef __cplusplus -#include -#include -#include "utility/LowPower.h" -#endif #ifdef DEBUG -#define debug(x,...) debugPrint(x, ##__VA_ARGS__) +#define debug(x,...) hw.debugPrint(isGateway, x, ##__VA_ARGS__) #else #define debug(x,...) #endif -#define BAUD_RATE 115200 // EEPROM start address for mysensors library data #define EEPROM_START 0 @@ -81,7 +74,7 @@ class MySensor * Creates a new instance of Sensor class. * */ - MySensor(MyTransport &radio =*new MyTransportNRF24(), MySigning &signer=*new MySigningNone()); + MySensor(MyTransport &radio =*new MyTransportNRF24(), MySigning &signer=*new MySigningNone(), MyHw &hw=*new MyHwATMega328()); /** * Begin operation of the MySensors library @@ -173,7 +166,7 @@ class MySensor * power cycles. * * You have 256 bytes to play with. Note that there is a limitation on the number - * of writes the EEPROM can handle (~100 000 cycles). + * of writes the EEPROM can handle (~100 000 cycles on ATMega328). * * @param pos The position to store value in (0-255) * @param Value to store in position @@ -193,11 +186,7 @@ class MySensor */ MyMessage& getLastMessage(void); - /** - * Sleep (PowerDownMode) the Arduino and radio. Wake up on timer. - * @param ms Number of milliseconds to sleep. - */ - void sleep(unsigned long ms); + /** * Wait for a specified amount of time to pass. Keeps process()ing. @@ -209,7 +198,13 @@ class MySensor void wait(unsigned long ms); /** - * Sleep (PowerDownMode) the Arduino and radio. Wake up on timer or pin change. + * Sleep (PowerDownMode) the MCU and radio. Wake up on timer. + * @param ms Number of milliseconds to sleep. + */ + void sleep(unsigned long ms); + + /** + * Sleep (PowerDownMode) the MCU and radio. Wake up on timer or pin change. * See: http://arduino.cc/en/Reference/attachInterrupt for details on modes and which pin * is assigned to what interrupt. On Nano/Pro Mini: 0=Pin2, 1=Pin3 * @param interrupt Interrupt that should trigger the wakeup @@ -220,7 +215,7 @@ class MySensor bool sleep(uint8_t interrupt, uint8_t mode, unsigned long ms=0); /** - * Sleep (PowerDownMode) the Arduino and radio. Wake up on timer or pin change for two separate interrupts. + * Sleep (PowerDownMode) the MCU and radio. Wake up on timer or pin change for two separate interrupts. * See: http://arduino.cc/en/Reference/attachInterrupt for details on modes and which pin * is assigned to what interrupt. On Nano/Pro Mini: 0=Pin2, 1=Pin3 * @param interrupt1 First interrupt that should trigger the wakeup @@ -232,10 +227,6 @@ class MySensor */ int8_t sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms=0); -#ifdef DEBUG - void debugPrint(const char *fmt, ... ); - int freeRam(); -#endif protected: NodeConfig nc; // Essential settings for node to work @@ -251,6 +242,7 @@ class MySensor MyTransport& radio; MySigning& signer; + MyHw& hw; void setupRepeaterMode(); boolean sendWrite(uint8_t dest, MyMessage &message); diff --git a/libraries/MySensors/MyTransport.h b/libraries/MySensors/MyTransport.h index 5c7b728..08ba0c6 100644 --- a/libraries/MySensors/MyTransport.h +++ b/libraries/MySensors/MyTransport.h @@ -17,7 +17,7 @@ #define BROADCAST_ADDRESS ((uint8_t)0xFF) class MyTransport -{ +{ public: // MyTransport constructor // different parameters would be needed depending on radio module (e.g. pins connected etc.) diff --git a/libraries/MySensors/examples/ClearEepromConfig/ClearEepromConfig.ino b/libraries/MySensors/examples/ClearEepromConfig/ClearEepromConfig.ino index 407d92d..ddbaaba 100644 --- a/libraries/MySensors/examples/ClearEepromConfig/ClearEepromConfig.ino +++ b/libraries/MySensors/examples/ClearEepromConfig/ClearEepromConfig.ino @@ -6,12 +6,16 @@ #include #include +#include void setup() { + Serial.begin(BAUD_RATE); + Serial.println("Started clearing. Please wait..."); for (int i=0;i<512;i++) { EEPROM.write(i, 0xff); } + Serial.println("Clering done. You're ready to go!"); } void loop() diff --git a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino index 3f0e94f..2bb49ab 100644 --- a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino +++ b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino @@ -1,6 +1,9 @@ // Example sketch showing how to control physical relays. // This example will remember relay state even after power failure. +#include +#include +#include #include #include @@ -9,7 +12,14 @@ #define RELAY_ON 1 // GPIO value to write to turn on attached relay #define RELAY_OFF 0 // GPIO value to write to turn off attached relay -MySensor gw; +// NRFRF24L01 radio driver (set low transmit power by default) +MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +// Message signing driver (none default) +MySigningNone signer; +// Select AtMega328 hardware profile +MyHwATMega328 hw; +// Construct MySensors library +MySensor gw(radio, signer, hw); void setup() { From c5760f72c61db703b225a92422bc46a0b39b5ebf Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 12 Mar 2015 23:58:38 +0100 Subject: [PATCH 071/137] Remove EEPROM buffer for routing information --- libraries/MySensors/MySensor.cpp | 33 +++++--------------------------- libraries/MySensors/MySensor.h | 6 ------ 2 files changed, 5 insertions(+), 34 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index bb69787..32645a3 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -37,6 +37,7 @@ static inline bool isValidDistance( const uint8_t distance ) { return distance != DISTANCE_INVALID; } + MySensor::MySensor(MyTransport &_radio, MySigning &_signer, MyHw &_hw) : radio(_radio), @@ -55,10 +56,6 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b // Only gateway should use node id 0 isGateway = _nodeId == 0; - if (repeaterMode) { - setupRepeaterMode(); - } - // Setup radio radio.init(); @@ -108,10 +105,6 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b debug(PSTR("%s started, id=%d, parent=%d, distance=%d\n"), isGateway?"gateway":(repeaterMode?"repeater":"sensor"), nc.nodeId, nc.parentNodeId, nc.distance); } -void MySensor::setupRepeaterMode(){ -// childNodeTable = new uint8_t[256]; - hw.readConfigBlock((void*)childNodeTable, (void *)EEPROM_ROUTES_ADDRESS, 256); -} uint8_t MySensor::getNodeId() { return nc.nodeId; @@ -213,7 +206,7 @@ boolean MySensor::sendRoute(MyMessage &message) { ok = sendWrite(nc.parentNodeId, message); } else { // Relay the message - uint8_t route = getChildRoute(dest); + uint8_t route = hw.readConfigByte(EEPROM_ROUTES_ADDRESS+dest); if (route > GATEWAY_ADDRESS && route < BROADCAST_ADDRESS) { // This message should be forwarded to a child node. If we send message // to this nodes pipe then all children will receive it because the are @@ -251,7 +244,7 @@ boolean MySensor::sendRoute(MyMessage &message) { // This message should be routed back towards sensor net gateway ok = sendWrite(nc.parentNodeId, message); // Add this child to our "routing table" if it not already exist - addChildRoute(sender, last); + hw.writeConfigByte(EEPROM_ROUTES_ADDRESS+sender, last); } } @@ -364,7 +357,7 @@ boolean MySensor::process() { if (repeaterMode && last != nc.parentNodeId) { // Message is from one of the child nodes. Add it to routing table. - addChildRoute(sender, last); + hw.writeConfigByte(EEPROM_ROUTES_ADDRESS+sender, last); } // Check if sender requests an ack back. @@ -458,7 +451,7 @@ boolean MySensor::process() { debug(PSTR("clear\n")); uint8_t i = 255; do { - removeChildRoute(i); + hw.writeConfigByte(EEPROM_ROUTES_ADDRESS+i, 0xff); } while (i--); // Clear parent node id & distance to gw hw.writeConfigByte(EEPROM_PARENT_NODE_ID_ADDRESS, 0xFF); @@ -509,22 +502,6 @@ uint8_t MySensor::loadState(uint8_t pos) { return hw.readConfigByte(EEPROM_LOCAL_CONFIG_ADDRESS+pos); } -void MySensor::addChildRoute(uint8_t childId, uint8_t route) { - childNodeTable[childId] = route; - hw.writeConfigByte(EEPROM_ROUTES_ADDRESS+childId, route); -} - -void MySensor::removeChildRoute(uint8_t childId) { - childNodeTable[childId] = 0xff; - hw.writeConfigByte(EEPROM_ROUTES_ADDRESS+childId, 0xff); -} - -uint8_t MySensor::getChildRoute(uint8_t childId) { - return childNodeTable[childId]; -} - - - void MySensor::wait(unsigned long ms) { unsigned long enter = hw.millisec(); while (hw.millisec() - enter < ms) { diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 5ccac1a..a58d93a 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -244,7 +244,6 @@ class MySensor MySigning& signer; MyHw& hw; - void setupRepeaterMode(); boolean sendWrite(uint8_t dest, MyMessage &message); private: @@ -252,7 +251,6 @@ class MySensor char convBuf[MAX_PAYLOAD*2+1]; #endif uint8_t failedTransmissions; - uint8_t childNodeTable[256]; // In memory buffer for routing information to other nodes. also stored in EEPROM void (*timeCallback)(unsigned long); // Callback for requested time messages void (*msgCallback)(const MyMessage &); // Callback for incoming messages from other nodes and gateway. @@ -260,10 +258,6 @@ class MySensor void setupNode(); void findParentNode(); uint8_t crc8Message(MyMessage &message); - uint8_t getChildRoute(uint8_t childId); - void addChildRoute(uint8_t childId, uint8_t route); - void removeChildRoute(uint8_t childId); - void internalSleep(unsigned long ms); bool sign(MyMessage &message); }; #endif From c1d5513578a809a2a2d8e68471964190d4d81073 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 12 Mar 2015 23:59:36 +0100 Subject: [PATCH 072/137] Remove LowPower dependency --- libraries/MySensors/MyHwATMega328.cpp | 70 +- libraries/MySensors/MyHwATMega328.h | 18 +- libraries/MySensors/utility/LowPower.cpp | 856 ----------------------- libraries/MySensors/utility/LowPower.h | 137 ---- 4 files changed, 73 insertions(+), 1008 deletions(-) delete mode 100644 libraries/MySensors/utility/LowPower.cpp delete mode 100644 libraries/MySensors/utility/LowPower.h diff --git a/libraries/MySensors/MyHwATMega328.cpp b/libraries/MySensors/MyHwATMega328.cpp index 3f42fc9..e5710cc 100644 --- a/libraries/MySensors/MyHwATMega328.cpp +++ b/libraries/MySensors/MyHwATMega328.cpp @@ -34,26 +34,69 @@ unsigned long MyHwATMega328::millisec() { } + +#define bodOn(mode) \ +do { \ + set_sleep_mode(mode); \ + cli(); \ + sleep_enable(); \ + sei(); \ + sleep_cpu(); \ + sleep_disable(); \ + sei(); \ +} while (0); + +#if defined __AVR_ATmega328P__ +#define bodOff(mode)\ +do { \ + set_sleep_mode(mode); \ + cli(); \ + sleep_enable(); \ + sleep_bod_disable(); \ + sei(); \ + sleep_cpu(); \ + sleep_disable(); \ + sei(); \ +} while (0); +#endif + +void powerDown(period_t period) { + + ADCSRA &= ~(1 << ADEN); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + #if defined __AVR_ATmega328P__ + bodOff(SLEEP_MODE_PWR_DOWN); + #else + bodOn(SLEEP_MODE_PWR_DOWN); + #endif + + ADCSRA |= (1 << ADEN); +} + void MyHwATMega328::sleep(unsigned long ms) { // Let serial prints finish (debug, log etc) Serial.flush(); pinIntTrigger = 0; - while (!pinIntTrigger && ms >= 8000) { LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); ms -= 8000; } - if (!pinIntTrigger && ms >= 4000) { LowPower.powerDown(SLEEP_4S, ADC_OFF, BOD_OFF); ms -= 4000; } - if (!pinIntTrigger && ms >= 2000) { LowPower.powerDown(SLEEP_2S, ADC_OFF, BOD_OFF); ms -= 2000; } - if (!pinIntTrigger && ms >= 1000) { LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF); ms -= 1000; } - if (!pinIntTrigger && ms >= 500) { LowPower.powerDown(SLEEP_500MS, ADC_OFF, BOD_OFF); ms -= 500; } - if (!pinIntTrigger && ms >= 250) { LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF); ms -= 250; } - if (!pinIntTrigger && ms >= 125) { LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_OFF); ms -= 120; } - if (!pinIntTrigger && ms >= 64) { LowPower.powerDown(SLEEP_60MS, ADC_OFF, BOD_OFF); ms -= 60; } - if (!pinIntTrigger && ms >= 32) { LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF); ms -= 30; } - if (!pinIntTrigger && ms >= 16) { LowPower.powerDown(SLEEP_15Ms, ADC_OFF, BOD_OFF); ms -= 15; } + while (!pinIntTrigger && ms >= 8000) { powerDown(SLEEP_8S); ms -= 8000; } + if (!pinIntTrigger && ms >= 4000) { powerDown(SLEEP_4S); ms -= 4000; } + if (!pinIntTrigger && ms >= 2000) { powerDown(SLEEP_2S); ms -= 2000; } + if (!pinIntTrigger && ms >= 1000) { powerDown(SLEEP_1S); ms -= 1000; } + if (!pinIntTrigger && ms >= 500) { powerDown(SLEEP_500MS); ms -= 500; } + if (!pinIntTrigger && ms >= 250) { powerDown(SLEEP_250MS); ms -= 250; } + if (!pinIntTrigger && ms >= 125) { powerDown(SLEEP_120MS); ms -= 120; } + if (!pinIntTrigger && ms >= 64) { powerDown(SLEEP_60MS); ms -= 60; } + if (!pinIntTrigger && ms >= 32) { powerDown(SLEEP_30MS); ms -= 30; } + if (!pinIntTrigger && ms >= 16) { powerDown(SLEEP_15Ms); ms -= 15; } } bool MyHwATMega328::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { // Let serial prints finish (debug, log etc) bool pinTriggeredWakeup = true; - Serial.flush(); attachInterrupt(interrupt, wakeUp, mode); if (ms>0) { pinIntTrigger = 0; @@ -63,7 +106,7 @@ bool MyHwATMega328::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { } } else { Serial.flush(); - LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); + powerDown(SLEEP_FOREVER); } detachInterrupt(interrupt); return pinTriggeredWakeup; @@ -71,7 +114,6 @@ bool MyHwATMega328::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { uint8_t MyHwATMega328::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) { int8_t retVal = 1; - Serial.flush(); // Let serial prints finish (debug, log etc) attachInterrupt(interrupt1, wakeUp, mode1); attachInterrupt(interrupt2, wakeUp2, mode2); if (ms>0) { @@ -82,7 +124,7 @@ uint8_t MyHwATMega328::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrup } } else { Serial.flush(); - LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); + powerDown(SLEEP_FOREVER); } detachInterrupt(interrupt1); detachInterrupt(interrupt2); diff --git a/libraries/MySensors/MyHwATMega328.h b/libraries/MySensors/MyHwATMega328.h index 90e6e82..bd197c7 100644 --- a/libraries/MySensors/MyHwATMega328.h +++ b/libraries/MySensors/MyHwATMega328.h @@ -5,8 +5,10 @@ #include "MyMessage.h" #include #include +#include +#include +#include #include -#include "utility/LowPower.h" #include "MyHw.h" @@ -15,6 +17,20 @@ #include #endif +enum period_t +{ + SLEEP_15Ms, + SLEEP_30MS, + SLEEP_60MS, + SLEEP_120MS, + SLEEP_250MS, + SLEEP_500MS, + SLEEP_1S, + SLEEP_2S, + SLEEP_4S, + SLEEP_8S, + SLEEP_FOREVER +}; class MyHwATMega328 : public MyHw { diff --git a/libraries/MySensors/utility/LowPower.cpp b/libraries/MySensors/utility/LowPower.cpp deleted file mode 100644 index a72cc31..0000000 --- a/libraries/MySensors/utility/LowPower.cpp +++ /dev/null @@ -1,856 +0,0 @@ -/******************************************************************************* -* LowPower Library -* Version: 1.30 -* Date: 22-05-2013 -* Company: Rocket Scream Electronics -* Website: www.rocketscream.com -* -* This is a lightweight low power library for Arduino. Please check our wiki -* (www.rocketscream.com/wiki) for more information on using this piece of -* library. -* -* This library is licensed under Creative Commons Attribution-ShareAlike 3.0 -* Unported License. -* -* Revision Description -* ======== =========== -* 1.30 Added support for ATMega168, ATMega2560, ATMega1280 & ATMega32U4. -* Tested to work with Arduino IDE 1.0.1 - 1.0.4. -* 1.20 Remove typo error in idle method for checking whether Timer 0 was -* turned off. -* Remove dependecy on WProgram.h which is not required. -* Tested to work with Arduino IDE 1.0. -* 1.10 Added #ifndef for sleep_bod_disable() for compatibility with future -* Arduino IDE release. -* 1.00 Initial public release. -*******************************************************************************/ -#include -#include -#include -#include -#include "LowPower.h" - -// Only Pico Power devices can change BOD settings through software -#if defined __AVR_ATmega328P__ -#ifndef sleep_bod_disable -#define sleep_bod_disable() \ -do { \ - unsigned char tempreg; \ - __asm__ __volatile__("in %[tempreg], %[mcucr]" "\n\t" \ - "ori %[tempreg], %[bods_bodse]" "\n\t" \ - "out %[mcucr], %[tempreg]" "\n\t" \ - "andi %[tempreg], %[not_bodse]" "\n\t" \ - "out %[mcucr], %[tempreg]" \ - : [tempreg] "=&d" (tempreg) \ - : [mcucr] "I" _SFR_IO_ADDR(MCUCR), \ - [bods_bodse] "i" (_BV(BODS) | _BV(BODSE)), \ - [not_bodse] "i" (~_BV(BODSE))); \ -} while (0) -#endif -#endif - -#define lowPowerBodOn(mode) \ -do { \ - set_sleep_mode(mode); \ - cli(); \ - sleep_enable(); \ - sei(); \ - sleep_cpu(); \ - sleep_disable(); \ - sei(); \ -} while (0); - -// Only Pico Power devices can change BOD settings through software -#if defined __AVR_ATmega328P__ -#define lowPowerBodOff(mode)\ -do { \ - set_sleep_mode(mode); \ - cli(); \ - sleep_enable(); \ - sleep_bod_disable(); \ - sei(); \ - sleep_cpu(); \ - sleep_disable(); \ - sei(); \ -} while (0); -#endif - -// Some macros is still missing from AVR GCC distribution for ATmega32U4 -#if defined __AVR_ATmega32U4__ - // Timer 4 PRR bit is currently not defined in iom32u4.h - #ifndef PRTIM4 - #define PRTIM4 4 - #endif - - // Timer 4 power reduction macro is not defined currently in power.h - #ifndef power_timer4_disable - #define power_timer4_disable() (PRR1 |= (uint8_t)(1 << PRTIM4)) - #endif - - #ifndef power_timer4_enable - #define power_timer4_enable() (PRR1 &= (uint8_t)~(1 << PRTIM4)) - #endif -#endif - -/******************************************************************************* -* Name: idle -* Description: Putting ATmega328P/168 into idle state. Please make sure you -* understand the implication and result of disabling module. -* -* Argument Description -* ========= =========== -* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake -* up resource: -* (a) SLEEP_15MS - 15 ms sleep -* (b) SLEEP_30MS - 30 ms sleep -* (c) SLEEP_60MS - 60 ms sleep -* (d) SLEEP_120MS - 120 ms sleep -* (e) SLEEP_250MS - 250 ms sleep -* (f) SLEEP_500MS - 500 ms sleep -* (g) SLEEP_1S - 1 s sleep -* (h) SLEEP_2S - 2 s sleep -* (i) SLEEP_4S - 4 s sleep -* (j) SLEEP_8S - 8 s sleep -* (k) SLEEP_FOREVER - Sleep without waking up through WDT -* -* 2. adc ADC module disable control: -* (a) ADC_OFF - Turn off ADC module -* (b) ADC_ON - Leave ADC module in its default state -* -* 3. timer2 Timer 2 module disable control: -* (a) TIMER2_OFF - Turn off Timer 2 module -* (b) TIMER2_ON - Leave Timer 2 module in its default state -* -* 4. timer1 Timer 1 module disable control: -* (a) TIMER1_OFF - Turn off Timer 1 module -* (b) TIMER1_ON - Leave Timer 1 module in its default state -* -* 5. timer0 Timer 0 module disable control: -* (a) TIMER0_OFF - Turn off Timer 0 module -* (b) TIMER0_ON - Leave Timer 0 module in its default state -* -* 6. spi SPI module disable control: -* (a) SPI_OFF - Turn off SPI module -* (b) SPI_ON - Leave SPI module in its default state -* -* 7. usart0 USART0 module disable control: -* (a) USART0_OFF - Turn off USART0 module -* (b) USART0_ON - Leave USART0 module in its default state -* -* 8. twi TWI module disable control: -* (a) TWI_OFF - Turn off TWI module -* (b) TWI_ON - Leave TWI module in its default state -* -*******************************************************************************/ -#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega168__) -void LowPowerClass::idle(period_t period, adc_t adc, timer2_t timer2, - timer1_t timer1, timer0_t timer0, - spi_t spi, usart0_t usart0, twi_t twi) -{ - // Temporary clock source variable - unsigned char clockSource = 0; - - if (timer2 == TIMER2_OFF) - { - if (TCCR2B & CS22) clockSource |= (1 << CS22); - if (TCCR2B & CS21) clockSource |= (1 << CS21); - if (TCCR2B & CS20) clockSource |= (1 << CS20); - - // Remove the clock source to shutdown Timer2 - TCCR2B &= ~(1 << CS22); - TCCR2B &= ~(1 << CS21); - TCCR2B &= ~(1 << CS20); - - power_timer2_disable(); - } - - if (adc == ADC_OFF) - { - ADCSRA &= ~(1 << ADEN); - power_adc_disable(); - } - - if (timer1 == TIMER1_OFF) power_timer1_disable(); - if (timer0 == TIMER0_OFF) power_timer0_disable(); - if (spi == SPI_OFF) power_spi_disable(); - if (usart0 == USART0_OFF) power_usart0_disable(); - if (twi == TWI_OFF) power_twi_disable(); - - if (period != SLEEP_FOREVER) - { - wdt_enable(period); - WDTCSR |= (1 << WDIE); - } - - lowPowerBodOn(SLEEP_MODE_IDLE); - - if (adc == ADC_OFF) - { - power_adc_enable(); - ADCSRA |= (1 << ADEN); - } - - if (timer2 == TIMER2_OFF) - { - if (clockSource & CS22) TCCR2B |= (1 << CS22); - if (clockSource & CS21) TCCR2B |= (1 << CS21); - if (clockSource & CS20) TCCR2B |= (1 << CS20); - - power_timer2_enable(); - } - - if (timer1 == TIMER1_OFF) power_timer1_enable(); - if (timer0 == TIMER0_OFF) power_timer0_enable(); - if (spi == SPI_OFF) power_spi_enable(); - if (usart0 == USART0_OFF) power_usart0_enable(); - if (twi == TWI_OFF) power_twi_enable(); -} -#endif - -/******************************************************************************* -* Name: idle -* Description: Putting ATmega32U4 into idle state. Please make sure you -* understand the implication and result of disabling module. -* Take note that Timer 2 is not available and USART0 -* is replaced with USART1 on ATmega32U4. -* -* Argument Description -* ========= =========== -* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake -* up resource: -* (a) SLEEP_15MS - 15 ms sleep -* (b) SLEEP_30MS - 30 ms sleep -* (c) SLEEP_60MS - 60 ms sleep -* (d) SLEEP_120MS - 120 ms sleep -* (e) SLEEP_250MS - 250 ms sleep -* (f) SLEEP_500MS - 500 ms sleep -* (g) SLEEP_1S - 1 s sleep -* (h) SLEEP_2S - 2 s sleep -* (i) SLEEP_4S - 4 s sleep -* (j) SLEEP_8S - 8 s sleep -* (k) SLEEP_FOREVER - Sleep without waking up through WDT -* -* 2. adc ADC module disable control: -* (a) ADC_OFF - Turn off ADC module -* (b) ADC_ON - Leave ADC module in its default state -* -* 3. timer4 Timer 4 module disable control: -* (a) TIMER4_OFF - Turn off Timer 4 module -* (b) TIMER4_ON - Leave Timer 4 module in its default state -* -* 4. timer3 Timer 3 module disable control: -* (a) TIMER3_OFF - Turn off Timer 3 module -* (b) TIMER3_ON - Leave Timer 3 module in its default state -* -* 5. timer1 Timer 1 module disable control: -* (a) TIMER1_OFF - Turn off Timer 1 module -* (b) TIMER1_ON - Leave Timer 1 module in its default state -* -* 6. timer0 Timer 0 module disable control: -* (a) TIMER0_OFF - Turn off Timer 0 module -* (b) TIMER0_ON - Leave Timer 0 module in its default state -* -* 7. spi SPI module disable control: -* (a) SPI_OFF - Turn off SPI module -* (b) SPI_ON - Leave SPI module in its default state -* -* 8. usart1 USART1 module disable control: -* (a) USART1_OFF - Turn off USART1 module -* (b) USART1_ON - Leave USART1 module in its default state -* -* 9. twi TWI module disable control: -* (a) TWI_OFF - Turn off TWI module -* (b) TWI_ON - Leave TWI module in its default state -* -* 10.usb USB module disable control: -* (a) USB_OFF - Turn off USB module -* (b) USB_ON - Leave USB module in its default state -*******************************************************************************/ -#if defined __AVR_ATmega32U4__ -void LowPowerClass::idle(period_t period, adc_t adc, - timer4_t timer4, timer3_t timer3, - timer1_t timer1, timer0_t timer0, - spi_t spi, usart1_t usart1, twi_t twi, usb_t usb) -{ - if (adc == ADC_OFF) - { - ADCSRA &= ~(1 << ADEN); - power_adc_disable(); - } - - if (timer4 == TIMER4_OFF) power_timer4_disable(); - if (timer3 == TIMER3_OFF) power_timer3_disable(); - if (timer1 == TIMER1_OFF) power_timer1_disable(); - if (timer0 == TIMER0_OFF) power_timer0_disable(); - if (spi == SPI_OFF) power_spi_disable(); - if (usart1 == USART1_OFF) power_usart1_disable(); - if (twi == TWI_OFF) power_twi_disable(); - if (usb == USB_OFF) power_usb_disable(); - - if (period != SLEEP_FOREVER) - { - wdt_enable(period); - WDTCSR |= (1 << WDIE); - } - - lowPowerBodOn(SLEEP_MODE_IDLE); - - if (adc == ADC_OFF) - { - power_adc_enable(); - ADCSRA |= (1 << ADEN); - } - - if (timer4 == TIMER4_OFF) power_timer4_enable(); - if (timer3 == TIMER3_OFF) power_timer3_enable(); - if (timer1 == TIMER1_OFF) power_timer1_enable(); - if (timer0 == TIMER0_OFF) power_timer0_enable(); - if (spi == SPI_OFF) power_spi_enable(); - if (usart1 == USART1_OFF) power_usart1_enable(); - if (twi == TWI_OFF) power_twi_enable(); - if (usb == USB_OFF) power_usb_enable(); -} -#endif - -/******************************************************************************* -* Name: idle -* Description: Putting ATmega2560 & ATmega1280 into idle state. Please make sure -* you understand the implication and result of disabling module. -* Take note that extra Timer 5, 4, 3 compared to an ATmega328P/168. -* Also take note that extra USART 3, 2, 1 compared to an -* ATmega328P/168. -* -* Argument Description -* ========= =========== -* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake -* up resource: -* (a) SLEEP_15MS - 15 ms sleep -* (b) SLEEP_30MS - 30 ms sleep -* (c) SLEEP_60MS - 60 ms sleep -* (d) SLEEP_120MS - 120 ms sleep -* (e) SLEEP_250MS - 250 ms sleep -* (f) SLEEP_500MS - 500 ms sleep -* (g) SLEEP_1S - 1 s sleep -* (h) SLEEP_2S - 2 s sleep -* (i) SLEEP_4S - 4 s sleep -* (j) SLEEP_8S - 8 s sleep -* (k) SLEEP_FOREVER - Sleep without waking up through WDT -* -* 2. adc ADC module disable control: -* (a) ADC_OFF - Turn off ADC module -* (b) ADC_ON - Leave ADC module in its default state -* -* 3. timer5 Timer 5 module disable control: -* (a) TIMER5_OFF - Turn off Timer 5 module -* (b) TIMER5_ON - Leave Timer 5 module in its default state -* -* 4. timer4 Timer 4 module disable control: -* (a) TIMER4_OFF - Turn off Timer 4 module -* (b) TIMER4_ON - Leave Timer 4 module in its default state -* -* 5. timer3 Timer 3 module disable control: -* (a) TIMER3_OFF - Turn off Timer 3 module -* (b) TIMER3_ON - Leave Timer 3 module in its default state -* -* 6. timer2 Timer 2 module disable control: -* (a) TIMER2_OFF - Turn off Timer 2 module -* (b) TIMER2_ON - Leave Timer 2 module in its default state -* -* 7. timer1 Timer 1 module disable control: -* (a) TIMER1_OFF - Turn off Timer 1 module -* (b) TIMER1_ON - Leave Timer 1 module in its default state -* -* 8. timer0 Timer 0 module disable control: -* (a) TIMER0_OFF - Turn off Timer 0 module -* (b) TIMER0_ON - Leave Timer 0 module in its default state -* -* 9. spi SPI module disable control: -* (a) SPI_OFF - Turn off SPI module -* (b) SPI_ON - Leave SPI module in its default state -* -* 10.usart3 USART3 module disable control: -* (a) USART3_OFF - Turn off USART3 module -* (b) USART3_ON - Leave USART3 module in its default state -* -* 11.usart2 USART2 module disable control: -* (a) USART2_OFF - Turn off USART2 module -* (b) USART2_ON - Leave USART2 module in its default state -* -* 12.usart1 USART1 module disable control: -* (a) USART1_OFF - Turn off USART1 module -* (b) USART1_ON - Leave USART1 module in its default state -* -* 13.usart0 USART0 module disable control: -* (a) USART0_OFF - Turn off USART0 module -* (b) USART0_ON - Leave USART0 module in its default state -* -* 14.twi TWI module disable control: -* (a) TWI_OFF - Turn off TWI module -* (b) TWI_ON - Leave TWI module in its default state -* -*******************************************************************************/ -#if defined (__AVR_ATmega2560__) || defined (__AVR_ATmega1280__) -void LowPowerClass::idle(period_t period, adc_t adc, timer5_t timer5, - timer4_t timer4, timer3_t timer3, timer2_t timer2, - timer1_t timer1, timer0_t timer0, spi_t spi, - usart3_t usart3, usart2_t usart2, usart1_t usart1, - usart0_t usart0, twi_t twi) -{ - // Temporary clock source variable - unsigned char clockSource = 0; - - if (timer2 == TIMER2_OFF) - { - if (TCCR2B & CS22) clockSource |= (1 << CS22); - if (TCCR2B & CS21) clockSource |= (1 << CS21); - if (TCCR2B & CS20) clockSource |= (1 << CS20); - - // Remove the clock source to shutdown Timer2 - TCCR2B &= ~(1 << CS22); - TCCR2B &= ~(1 << CS21); - TCCR2B &= ~(1 << CS20); - - power_timer2_disable(); - } - - if (adc == ADC_OFF) - { - ADCSRA &= ~(1 << ADEN); - power_adc_disable(); - } - - if (timer5 == TIMER5_OFF) power_timer5_disable(); - if (timer4 == TIMER4_OFF) power_timer4_disable(); - if (timer3 == TIMER3_OFF) power_timer3_disable(); - if (timer1 == TIMER1_OFF) power_timer1_disable(); - if (timer0 == TIMER0_OFF) power_timer0_disable(); - if (spi == SPI_OFF) power_spi_disable(); - if (usart3 == USART3_OFF) power_usart3_disable(); - if (usart2 == USART2_OFF) power_usart2_disable(); - if (usart1 == USART1_OFF) power_usart1_disable(); - if (usart0 == USART0_OFF) power_usart0_disable(); - if (twi == TWI_OFF) power_twi_disable(); - - if (period != SLEEP_FOREVER) - { - wdt_enable(period); - WDTCSR |= (1 << WDIE); - } - - lowPowerBodOn(SLEEP_MODE_IDLE); - - if (adc == ADC_OFF) - { - power_adc_enable(); - ADCSRA |= (1 << ADEN); - } - - if (timer2 == TIMER2_OFF) - { - if (clockSource & CS22) TCCR2B |= (1 << CS22); - if (clockSource & CS21) TCCR2B |= (1 << CS21); - if (clockSource & CS20) TCCR2B |= (1 << CS20); - - power_timer2_enable(); - } - - if (timer5 == TIMER5_OFF) power_timer5_enable(); - if (timer4 == TIMER4_OFF) power_timer4_enable(); - if (timer3 == TIMER3_OFF) power_timer3_enable(); - if (timer1 == TIMER1_OFF) power_timer1_enable(); - if (timer0 == TIMER0_OFF) power_timer0_enable(); - if (spi == SPI_OFF) power_spi_enable(); - if (usart3 == USART3_OFF) power_usart3_enable(); - if (usart2 == USART2_OFF) power_usart2_enable(); - if (usart1 == USART1_OFF) power_usart1_enable(); - if (usart0 == USART0_OFF) power_usart0_enable(); - if (twi == TWI_OFF) power_twi_enable(); -} -#endif - -/******************************************************************************* -* Name: adcNoiseReduction -* Description: Putting microcontroller into ADC noise reduction state. This is -* a very useful state when using the ADC to achieve best and low -* noise signal. -* -* Argument Description -* ========= =========== -* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake -* up resource: -* (a) SLEEP_15MS - 15 ms sleep -* (b) SLEEP_30MS - 30 ms sleep -* (c) SLEEP_60MS - 60 ms sleep -* (d) SLEEP_120MS - 120 ms sleep -* (e) SLEEP_250MS - 250 ms sleep -* (f) SLEEP_500MS - 500 ms sleep -* (g) SLEEP_1S - 1 s sleep -* (h) SLEEP_2S - 2 s sleep -* (i) SLEEP_4S - 4 s sleep -* (j) SLEEP_8S - 8 s sleep -* (k) SLEEP_FOREVER - Sleep without waking up through WDT -* -* 2. adc ADC module disable control. Turning off the ADC module is -* basically removing the purpose of this low power mode. -* (a) ADC_OFF - Turn off ADC module -* (b) ADC_ON - Leave ADC module in its default state -* -* 3. timer2 Timer 2 module disable control: -* (a) TIMER2_OFF - Turn off Timer 2 module -* (b) TIMER2_ON - Leave Timer 2 module in its default state -* -*******************************************************************************/ -void LowPowerClass::adcNoiseReduction(period_t period, adc_t adc, - timer2_t timer2) -{ - // Temporary clock source variable - unsigned char clockSource = 0; - - #if !defined(__AVR_ATmega32U4__) - if (timer2 == TIMER2_OFF) - { - if (TCCR2B & CS22) clockSource |= (1 << CS22); - if (TCCR2B & CS21) clockSource |= (1 << CS21); - if (TCCR2B & CS20) clockSource |= (1 << CS20); - - // Remove the clock source to shutdown Timer2 - TCCR2B &= ~(1 << CS22); - TCCR2B &= ~(1 << CS21); - TCCR2B &= ~(1 << CS20); - } - #endif - - if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); - - if (period != SLEEP_FOREVER) - { - wdt_enable(period); - WDTCSR |= (1 << WDIE); - } - - lowPowerBodOn(SLEEP_MODE_ADC); - - if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); - - #if !defined(__AVR_ATmega32U4__) - if (timer2 == TIMER2_OFF) - { - if (clockSource & CS22) TCCR2B |= (1 << CS22); - if (clockSource & CS21) TCCR2B |= (1 << CS21); - if (clockSource & CS20) TCCR2B |= (1 << CS20); - - } - #endif -} - -/******************************************************************************* -* Name: powerDown -* Description: Putting microcontroller into power down state. This is -* the lowest current consumption state. Use this together with -* external pin interrupt to wake up through external event -* triggering (example: RTC clockout pin, SD card detect pin). -* -* Argument Description -* ========= =========== -* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake -* up resource: -* (a) SLEEP_15MS - 15 ms sleep -* (b) SLEEP_30MS - 30 ms sleep -* (c) SLEEP_60MS - 60 ms sleep -* (d) SLEEP_120MS - 120 ms sleep -* (e) SLEEP_250MS - 250 ms sleep -* (f) SLEEP_500MS - 500 ms sleep -* (g) SLEEP_1S - 1 s sleep -* (h) SLEEP_2S - 2 s sleep -* (i) SLEEP_4S - 4 s sleep -* (j) SLEEP_8S - 8 s sleep -* (k) SLEEP_FOREVER - Sleep without waking up through WDT -* -* 2. adc ADC module disable control. Turning off the ADC module is -* basically removing the purpose of this low power mode. -* (a) ADC_OFF - Turn off ADC module -* (b) ADC_ON - Leave ADC module in its default state -* -* 3. bod Brown Out Detector (BOD) module disable control: -* (a) BOD_OFF - Turn off BOD module -* (b) BOD_ON - Leave BOD module in its default state -* -*******************************************************************************/ -void LowPowerClass::powerDown(period_t period, adc_t adc, bod_t bod) -{ - if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); - - if (period != SLEEP_FOREVER) - { - wdt_enable(period); - WDTCSR |= (1 << WDIE); - } - if (bod == BOD_OFF) - { - #if defined __AVR_ATmega328P__ - lowPowerBodOff(SLEEP_MODE_PWR_DOWN); - #else - lowPowerBodOn(SLEEP_MODE_PWR_DOWN); - #endif - } - else - { - lowPowerBodOn(SLEEP_MODE_PWR_DOWN); - } - - if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); -} - -/******************************************************************************* -* Name: powerSave -* Description: Putting microcontroller into power save state. This is -* the lowest current consumption state after power down. -* Use this state together with an external 32.768 kHz crystal (but -* 8/16 MHz crystal/resonator need to be removed) to provide an -* asynchronous clock source to Timer 2. Please take note that -* Timer 2 is also used by the Arduino core for PWM operation. -* Please refer to wiring.c for explanation. Removal of the external -* 8/16 MHz crystal/resonator requires the microcontroller to run -* on its internal RC oscillator which is not so accurate for time -* critical operation. -* -* Argument Description -* ========= =========== -* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake -* up resource: -* (a) SLEEP_15MS - 15 ms sleep -* (b) SLEEP_30MS - 30 ms sleep -* (c) SLEEP_60MS - 60 ms sleep -* (d) SLEEP_120MS - 120 ms sleep -* (e) SLEEP_250MS - 250 ms sleep -* (f) SLEEP_500MS - 500 ms sleep -* (g) SLEEP_1S - 1 s sleep -* (h) SLEEP_2S - 2 s sleep -* (i) SLEEP_4S - 4 s sleep -* (j) SLEEP_8S - 8 s sleep -* (k) SLEEP_FOREVER - Sleep without waking up through WDT -* -* 2. adc ADC module disable control. Turning off the ADC module is -* basically removing the purpose of this low power mode. -* (a) ADC_OFF - Turn off ADC module -* (b) ADC_ON - Leave ADC module in its default state -* -* 3. bod Brown Out Detector (BOD) module disable control: -* (a) BOD_OFF - Turn off BOD module -* (b) BOD_ON - Leave BOD module in its default state -* -* 4. timer2 Timer 2 module disable control: -* (a) TIMER2_OFF - Turn off Timer 2 module -* (b) TIMER2_ON - Leave Timer 2 module in its default state -* -*******************************************************************************/ -void LowPowerClass::powerSave(period_t period, adc_t adc, bod_t bod, - timer2_t timer2) -{ - // Temporary clock source variable - unsigned char clockSource = 0; - - #if !defined(__AVR_ATmega32U4__) - if (timer2 == TIMER2_OFF) - { - if (TCCR2B & CS22) clockSource |= (1 << CS22); - if (TCCR2B & CS21) clockSource |= (1 << CS21); - if (TCCR2B & CS20) clockSource |= (1 << CS20); - - // Remove the clock source to shutdown Timer2 - TCCR2B &= ~(1 << CS22); - TCCR2B &= ~(1 << CS21); - TCCR2B &= ~(1 << CS20); - } - #endif - - if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); - - if (period != SLEEP_FOREVER) - { - wdt_enable(period); - WDTCSR |= (1 << WDIE); - } - - if (bod == BOD_OFF) - { - #if defined __AVR_ATmega328P__ - lowPowerBodOff(SLEEP_MODE_PWR_SAVE); - #else - lowPowerBodOn(SLEEP_MODE_PWR_SAVE); - #endif - } - else - { - lowPowerBodOn(SLEEP_MODE_PWR_SAVE); - } - - if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); - - #if !defined(__AVR_ATmega32U4__) - if (timer2 == TIMER2_OFF) - { - if (clockSource & CS22) TCCR2B |= (1 << CS22); - if (clockSource & CS21) TCCR2B |= (1 << CS21); - if (clockSource & CS20) TCCR2B |= (1 << CS20); - } - #endif -} - -/******************************************************************************* -* Name: powerStandby -* Description: Putting microcontroller into power standby state. -* -* Argument Description -* ========= =========== -* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake -* up resource: -* (a) SLEEP_15MS - 15 ms sleep -* (b) SLEEP_30MS - 30 ms sleep -* (c) SLEEP_60MS - 60 ms sleep -* (d) SLEEP_120MS - 120 ms sleep -* (e) SLEEP_250MS - 250 ms sleep -* (f) SLEEP_500MS - 500 ms sleep -* (g) SLEEP_1S - 1 s sleep -* (h) SLEEP_2S - 2 s sleep -* (i) SLEEP_4S - 4 s sleep -* (j) SLEEP_8S - 8 s sleep -* (k) SLEEP_FOREVER - Sleep without waking up through WDT -* -* 2. adc ADC module disable control. Turning off the ADC module is -* basically removing the purpose of this low power mode. -* (a) ADC_OFF - Turn off ADC module -* (b) ADC_ON - Leave ADC module in its default state -* -* 3. bod Brown Out Detector (BOD) module disable control: -* (a) BOD_OFF - Turn off BOD module -* (b) BOD_ON - Leave BOD module in its default state -* -*******************************************************************************/ -void LowPowerClass::powerStandby(period_t period, adc_t adc, bod_t bod) -{ - if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); - - if (period != SLEEP_FOREVER) - { - wdt_enable(period); - WDTCSR |= (1 << WDIE); - } - - if (bod == BOD_OFF) - { - #if defined __AVR_ATmega328P__ - lowPowerBodOff(SLEEP_MODE_STANDBY); - #else - lowPowerBodOn(SLEEP_MODE_STANDBY); - #endif - } - else - { - lowPowerBodOn(SLEEP_MODE_STANDBY); - } - - if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); -} - -/******************************************************************************* -* Name: powerExtStandby -* Description: Putting microcontroller into power extended standby state. This -* is different from the power standby state as it has the -* capability to run Timer 2 asynchronously. -* -* Argument Description -* ========= =========== -* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake -* up resource: -* (a) SLEEP_15MS - 15 ms sleep -* (b) SLEEP_30MS - 30 ms sleep -* (c) SLEEP_60MS - 60 ms sleep -* (d) SLEEP_120MS - 120 ms sleep -* (e) SLEEP_250MS - 250 ms sleep -* (f) SLEEP_500MS - 500 ms sleep -* (g) SLEEP_1S - 1 s sleep -* (h) SLEEP_2S - 2 s sleep -* (i) SLEEP_4S - 4 s sleep -* (j) SLEEP_8S - 8 s sleep -* (k) SLEEP_FOREVER - Sleep without waking up through WDT -* -* 2. adc ADC module disable control. -* (a) ADC_OFF - Turn off ADC module -* (b) ADC_ON - Leave ADC module in its default state -* -* 3. bod Brown Out Detector (BOD) module disable control: -* (a) BOD_OFF - Turn off BOD module -* (b) BOD_ON - Leave BOD module in its default state -* -* 4. timer2 Timer 2 module disable control: -* (a) TIMER2_OFF - Turn off Timer 2 module -* (b) TIMER2_ON - Leave Timer 2 module in its default state -* -*******************************************************************************/ -void LowPowerClass::powerExtStandby(period_t period, adc_t adc, bod_t bod, - timer2_t timer2) -{ - // Temporary clock source variable - unsigned char clockSource = 0; - - #if !defined(__AVR_ATmega32U4__) - if (timer2 == TIMER2_OFF) - { - if (TCCR2B & CS22) clockSource |= (1 << CS22); - if (TCCR2B & CS21) clockSource |= (1 << CS21); - if (TCCR2B & CS20) clockSource |= (1 << CS20); - - // Remove the clock source to shutdown Timer2 - TCCR2B &= ~(1 << CS22); - TCCR2B &= ~(1 << CS21); - TCCR2B &= ~(1 << CS20); - } - #endif - - if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); - - if (period != SLEEP_FOREVER) - { - wdt_enable(period); - WDTCSR |= (1 << WDIE); - } - if (bod == BOD_OFF) - { - #if defined __AVR_ATmega328P__ - lowPowerBodOff(SLEEP_MODE_EXT_STANDBY); - #else - lowPowerBodOn(SLEEP_MODE_EXT_STANDBY); - #endif - } - else - { - lowPowerBodOn(SLEEP_MODE_EXT_STANDBY); - } - - if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); - - #if !defined(__AVR_ATmega32U4__) - if (timer2 == TIMER2_OFF) - { - if (clockSource & CS22) TCCR2B |= (1 << CS22); - if (clockSource & CS21) TCCR2B |= (1 << CS21); - if (clockSource & CS20) TCCR2B |= (1 << CS20); - } - #endif -} - -/******************************************************************************* -* Name: ISR (WDT_vect) -* Description: Watchdog Timer interrupt service routine. This routine is -* required to allow automatic WDIF and WDIE bit clearance in -* hardware. -* -*******************************************************************************/ -ISR (WDT_vect) -{ - // WDIE & WDIF is cleared in hardware upon entering this ISR - wdt_disable(); -} - -LowPowerClass LowPower; \ No newline at end of file diff --git a/libraries/MySensors/utility/LowPower.h b/libraries/MySensors/utility/LowPower.h deleted file mode 100644 index ef05901..0000000 --- a/libraries/MySensors/utility/LowPower.h +++ /dev/null @@ -1,137 +0,0 @@ -#ifndef LowPower_h -#define LowPower_h - -enum period_t -{ - SLEEP_15Ms, - SLEEP_30MS, - SLEEP_60MS, - SLEEP_120MS, - SLEEP_250MS, - SLEEP_500MS, - SLEEP_1S, - SLEEP_2S, - SLEEP_4S, - SLEEP_8S, - SLEEP_FOREVER -}; - -enum bod_t -{ - BOD_OFF, - BOD_ON -}; - -enum adc_t -{ - ADC_OFF, - ADC_ON -}; - -enum timer5_t -{ - TIMER5_OFF, - TIMER5_ON -}; - -enum timer4_t -{ - TIMER4_OFF, - TIMER4_ON -}; - -enum timer3_t -{ - TIMER3_OFF, - TIMER3_ON -}; - -enum timer2_t -{ - TIMER2_OFF, - TIMER2_ON -}; - -enum timer1_t -{ - TIMER1_OFF, - TIMER1_ON -}; - -enum timer0_t -{ - TIMER0_OFF, - TIMER0_ON -}; - -enum spi_t -{ - SPI_OFF, - SPI_ON -}; - -enum usart0_t -{ - USART0_OFF, - USART0_ON -}; - -enum usart1_t -{ - USART1_OFF, - USART1_ON -}; - -enum usart2_t -{ - USART2_OFF, - USART2_ON -}; - -enum usart3_t -{ - USART3_OFF, - USART3_ON -}; - -enum twi_t -{ - TWI_OFF, - TWI_ON -}; - -enum usb_t -{ - USB_OFF, - USB_ON -}; - -class LowPowerClass -{ - public: - #if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega168__) - void idle(period_t period, adc_t adc, timer2_t timer2, - timer1_t timer1, timer0_t timer0, spi_t spi, - usart0_t usart0, twi_t twi); - #elif defined __AVR_ATmega2560__ - void idle(period_t period, adc_t adc, timer5_t timer5, - timer4_t timer4, timer3_t timer3, timer2_t timer2, - timer1_t timer1, timer0_t timer0, spi_t spi, - usart3_t usart3, usart2_t usart2, usart1_t usart1, - usart0_t usart0, twi_t twi); - #elif defined __AVR_ATmega32U4__ - void idle(period_t period, adc_t adc, timer4_t timer4, timer3_t timer3, - timer1_t timer1, timer0_t timer0, spi_t spi, - usart1_t usart1, twi_t twi, usb_t usb); - #else - #error "Please ensure chosen MCU is either 328P, 32U4 or 2560." - #endif - void adcNoiseReduction(period_t period, adc_t adc, timer2_t timer2); - void powerDown(period_t period, adc_t adc, bod_t bod); - void powerSave(period_t period, adc_t adc, bod_t bod, timer2_t timer2); - void powerStandby(period_t period, adc_t adc, bod_t bod); - void powerExtStandby(period_t period, adc_t adc, bod_t bod, timer2_t timer2); -}; - -extern LowPowerClass LowPower; -#endif \ No newline at end of file From d88e9175440627bd30a48456a393f979bad77ae9 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Fri, 13 Mar 2015 15:39:05 +0100 Subject: [PATCH 073/137] Simplify thinga a bit --- libraries/MySensors/MyHwATMega328.cpp | 67 ++++++++++++--------------- 1 file changed, 29 insertions(+), 38 deletions(-) diff --git a/libraries/MySensors/MyHwATMega328.cpp b/libraries/MySensors/MyHwATMega328.cpp index e5710cc..7b03cd7 100644 --- a/libraries/MySensors/MyHwATMega328.cpp +++ b/libraries/MySensors/MyHwATMega328.cpp @@ -16,50 +16,24 @@ MyHwATMega328::MyHwATMega328() : MyHw() } -void MyHwATMega328::init() { +inline void MyHwATMega328::init() { Serial.begin(BAUD_RATE); } -void MyHwATMega328::watchdogReset() { +inline void MyHwATMega328::watchdogReset() { wdt_reset(); } -void MyHwATMega328::reboot() { +inline void MyHwATMega328::reboot() { wdt_enable(WDTO_15MS); for (;;); } -unsigned long MyHwATMega328::millisec() { +inline unsigned long MyHwATMega328::millisec() { return millis(); } - -#define bodOn(mode) \ -do { \ - set_sleep_mode(mode); \ - cli(); \ - sleep_enable(); \ - sei(); \ - sleep_cpu(); \ - sleep_disable(); \ - sei(); \ -} while (0); - -#if defined __AVR_ATmega328P__ -#define bodOff(mode)\ -do { \ - set_sleep_mode(mode); \ - cli(); \ - sleep_enable(); \ - sleep_bod_disable(); \ - sei(); \ - sleep_cpu(); \ - sleep_disable(); \ - sei(); \ -} while (0); -#endif - void powerDown(period_t period) { ADCSRA &= ~(1 << ADEN); @@ -70,15 +44,32 @@ void powerDown(period_t period) { WDTCSR |= (1 << WDIE); } #if defined __AVR_ATmega328P__ - bodOff(SLEEP_MODE_PWR_DOWN); + do { + set_sleep_mode(SLEEP_MODE_PWR_DOWN); + cli(); + sleep_enable(); + sleep_bod_disable(); + sei(); + sleep_cpu(); + sleep_disable(); + sei(); + } while (0); #else - bodOn(SLEEP_MODE_PWR_DOWN); + do { + set_sleep_mode(SLEEP_MODE_PWR_DOWN); + cli(); + sleep_enable(); + sei(); + sleep_cpu(); + sleep_disable(); + sei(); + } while (0); #endif ADCSRA |= (1 << ADEN); } -void MyHwATMega328::sleep(unsigned long ms) { +inline void MyHwATMega328::sleep(unsigned long ms) { // Let serial prints finish (debug, log etc) Serial.flush(); pinIntTrigger = 0; @@ -112,7 +103,7 @@ bool MyHwATMega328::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { return pinTriggeredWakeup; } -uint8_t MyHwATMega328::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) { +inline uint8_t MyHwATMega328::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) { int8_t retVal = 1; attachInterrupt(interrupt1, wakeUp, mode1); attachInterrupt(interrupt2, wakeUp2, mode2); @@ -137,19 +128,19 @@ uint8_t MyHwATMega328::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrup return retVal; } -uint8_t MyHwATMega328::readConfigByte(uint8_t pos) { +inline uint8_t MyHwATMega328::readConfigByte(uint8_t pos) { return eeprom_read_byte((uint8_t*)pos); } -void MyHwATMega328::writeConfigByte(uint8_t pos, uint8_t value) { +inline void MyHwATMega328::writeConfigByte(uint8_t pos, uint8_t value) { eeprom_update_byte((uint8_t*)pos, value); } -void MyHwATMega328::readConfigBlock(void* buf, void * pos, size_t length) { +inline void MyHwATMega328::readConfigBlock(void* buf, void * pos, size_t length) { eeprom_read_block(buf, (void*)pos, length); } -void MyHwATMega328::writeConfigBlock(void* pos, void* buf, size_t length) { +inline void MyHwATMega328::writeConfigBlock(void* pos, void* buf, size_t length) { eeprom_write_block((void*)pos, (void*)buf, length); } From 5ae55e5b8a54abdc30986e7665677977848a99a6 Mon Sep 17 00:00:00 2001 From: Marcelo Aquino Date: Fri, 13 Mar 2015 16:09:09 -0300 Subject: [PATCH 074/137] add DigitalIO.h to MQTTGateway --- libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index bb1ea20..169ad89 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -56,9 +56,11 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway */ +#include +#include + #include #include -#include #include #include #include From 73024ea4c98ed45308c3708ffc0479029cf524b2 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 16 Mar 2015 10:43:09 +0100 Subject: [PATCH 075/137] Weird compile error for Patrick --- libraries/MySensors/MyConfig.h | 10 ++++-- libraries/MySensors/MyHw.h | 11 +++--- libraries/MySensors/MyHwATMega328.cpp | 44 +++++++++++++---------- libraries/MySensors/MyHwATMega328.h | 25 +++++++++---- libraries/MySensors/MySensor.cpp | 52 +++++++++++++-------------- libraries/MySensors/MySensor.h | 5 ++- 6 files changed, 85 insertions(+), 62 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 3e09981..0b4d806 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -1,13 +1,17 @@ #ifndef MyConfig_h #define MyConfig_h #include -/********************************** -* Enable/Disable debug logging -***********************************/ + +// Enable debug flag for debug prints. This will add a lot to the size of the final sketch but good +// to see what is actually is happening when developing #define DEBUG +// Serial output baud rate #define BAUD_RATE 115200 +// Set the hardware driver to use (initialized by MySensor-class) +#include "MyHwATMega328.h" +typedef MyHwATMega328 MyHwDriver; /********************************** * Message Signing Settings diff --git a/libraries/MySensors/MyHw.h b/libraries/MySensors/MyHw.h index a7ce870..95cf2a4 100644 --- a/libraries/MySensors/MyHw.h +++ b/libraries/MySensors/MyHw.h @@ -15,17 +15,18 @@ class MyHw public: // MyHw constructor MyHw(); - virtual void init() = 0; +/* // The following is defined as macros to save space + virtual void init() = 0; virtual void watchdogReset() = 0; virtual void reboot() = 0; virtual unsigned long millisec() = 0; + virtual uint8_t readConfig(uint8_t pos) = 0; + virtual void writeConfig(uint8_t pos, uint8_t value) = 0; + virtual void readConfigBlock(void* buf, void * pos, size_t length) = 0; + virtual void writeConfigBlock(void* pos, void* buf, uint16_t length) = 0; */ virtual void sleep(unsigned long ms) = 0; virtual bool sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) = 0; virtual uint8_t sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) = 0; - virtual uint8_t readConfigByte(uint8_t pos) = 0; - virtual void writeConfigByte(uint8_t pos, uint8_t value) = 0; - virtual void readConfigBlock(void* buf, void * pos, size_t length) = 0; - virtual void writeConfigBlock(void* pos, void* buf, uint16_t length) = 0; #ifdef DEBUG virtual void debugPrint(bool isGW, const char *fmt, ... ) = 0; #endif diff --git a/libraries/MySensors/MyHwATMega328.cpp b/libraries/MySensors/MyHwATMega328.cpp index 7b03cd7..4f9d9a8 100644 --- a/libraries/MySensors/MyHwATMega328.cpp +++ b/libraries/MySensors/MyHwATMega328.cpp @@ -16,6 +16,27 @@ MyHwATMega328::MyHwATMega328() : MyHw() } +/* + +// The following was redifined as macros to save space + +inline uint8_t MyHwATMega328::readConfig(uint8_t pos) { + return eeprom_read_byte((uint8_t*)pos); +} + +inline void MyHwATMega328::writeConfig(uint8_t pos, uint8_t value) { + eeprom_update_byte((uint8_t*)pos, value); +} + +inline void MyHwATMega328::readConfigBlock(void* buf, void * pos, size_t length) { + eeprom_read_block(buf, (void*)pos, length); +} + +inline void MyHwATMega328::writeConfigBlock(void* pos, void* buf, size_t length) { + eeprom_write_block((void*)pos, (void*)buf, length); +} + + inline void MyHwATMega328::init() { Serial.begin(BAUD_RATE); } @@ -25,13 +46,13 @@ inline void MyHwATMega328::watchdogReset() { } inline void MyHwATMega328::reboot() { - wdt_enable(WDTO_15MS); - for (;;); + wdt_enable(WDTO_15MS); for (;;); } -inline unsigned long MyHwATMega328::millisec() { - return millis(); +inline unsigned long MyHwATMega328::millis() { + return ::millis(); } +*/ void powerDown(period_t period) { @@ -128,21 +149,6 @@ inline uint8_t MyHwATMega328::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t i return retVal; } -inline uint8_t MyHwATMega328::readConfigByte(uint8_t pos) { - return eeprom_read_byte((uint8_t*)pos); -} - -inline void MyHwATMega328::writeConfigByte(uint8_t pos, uint8_t value) { - eeprom_update_byte((uint8_t*)pos, value); -} - -inline void MyHwATMega328::readConfigBlock(void* buf, void * pos, size_t length) { - eeprom_read_block(buf, (void*)pos, length); -} - -inline void MyHwATMega328::writeConfigBlock(void* pos, void* buf, size_t length) { - eeprom_write_block((void*)pos, (void*)buf, length); -} #ifdef DEBUG diff --git a/libraries/MySensors/MyHwATMega328.h b/libraries/MySensors/MyHwATMega328.h index bd197c7..618a789 100644 --- a/libraries/MySensors/MyHwATMega328.h +++ b/libraries/MySensors/MyHwATMega328.h @@ -17,6 +17,18 @@ #include #endif +// Define these as macros to save valuable space +#define hw_init() Serial.begin(BAUD_RATE) +#define hw_watchdogReset() wdt_reset() +#define hw_reboot() wdt_enable(WDTO_15MS); for (;;) +#define hw_millis() millis() +#define hw_readConfig(__pos) eeprom_read_byte((uint8_t*)__pos) +#define hw_writeConfig(__pos, __value) eeprom_update_byte((uint8_t*)__pos, __value) +#define hw_readConfigBlock(__buf, __pos, __length) eeprom_read_block(buf, (void*)__pos, __length) +#define hw_writeConfigBlock(__pos, __buf, __length) eeprom_write_block((void*)__pos, (void*)__buf, __length) + + + enum period_t { SLEEP_15Ms, @@ -37,17 +49,18 @@ class MyHwATMega328 : public MyHw public: MyHwATMega328(); - void init(); +/* void init(); void watchdogReset(); void reboot(); - unsigned long millisec(); + unsigned long millis(); + uint8_t readConfig(uint8_t pos); + void writeConfig(uint8_t pos, uint8_t value); + void readConfigBlock(void* buf, void * pos, size_t length); + void writeConfigBlock(void* pos, void* buf, size_t length); */ + void sleep(unsigned long ms); bool sleep(uint8_t interrupt, uint8_t mode, unsigned long ms); uint8_t sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms); - uint8_t readConfigByte(uint8_t pos); - void writeConfigByte(uint8_t pos, uint8_t value); - void readConfigBlock(void* buf, void * pos, size_t length); - void writeConfigBlock(void* pos, void* buf, size_t length); #ifdef DEBUG void debugPrint(bool isGW, const char *fmt, ... ); #endif diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 32645a3..c058e2e 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -48,7 +48,7 @@ MySensor::MySensor(MyTransport &_radio, MySigning &_signer, MyHw &_hw) void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId) { - hw.init(); + hw_init(); repeaterMode = _repeaterMode; msgCallback = _msgCallback; failedTransmissions = 0; @@ -60,11 +60,11 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b radio.init(); // Read settings from eeprom - hw.readConfigBlock((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); + hw_readConfigBlock((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); // Read latest received controller configuration from EEPROM - hw.readConfigBlock((void*)&cc, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS, sizeof(ControllerConfig)); + hw_readConfigBlock((void*)&cc, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS, sizeof(ControllerConfig)); // Read out the signing requirements from EEPROM - hw.readConfigBlock((void*)doSign, (void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, sizeof(doSign)); + hw_readConfigBlock((void*)doSign, (void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, sizeof(doSign)); if (isGateway) { nc.distance = 0; @@ -79,7 +79,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b if (!autoFindParent) { nc.parentNodeId = _parentNodeId; // Save static parent id in eeprom (used by bootloader) - hw.writeConfigByte(EEPROM_PARENT_NODE_ID_ADDRESS, _parentNodeId); + hw_writeConfig(EEPROM_PARENT_NODE_ID_ADDRESS, _parentNodeId); // We don't actually know the distance to gw here. Let's pretend it is 1. // If the current node is also repeater, be aware of this. nc.distance = 1; @@ -94,7 +94,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b nc.nodeId = _nodeId; // Save static id in eeprom if (_nodeId > 0) - hw.writeConfigByte(EEPROM_NODE_ID_ADDRESS, _nodeId); + hw_writeConfig(EEPROM_NODE_ID_ADDRESS, _nodeId); } else if (isValidParent(nc.parentNodeId)) { // Try to fetch node-id from gateway requestNodeId(); @@ -206,7 +206,7 @@ boolean MySensor::sendRoute(MyMessage &message) { ok = sendWrite(nc.parentNodeId, message); } else { // Relay the message - uint8_t route = hw.readConfigByte(EEPROM_ROUTES_ADDRESS+dest); + uint8_t route = hw_readConfig(EEPROM_ROUTES_ADDRESS+dest); if (route > GATEWAY_ADDRESS && route < BROADCAST_ADDRESS) { // This message should be forwarded to a child node. If we send message // to this nodes pipe then all children will receive it because the are @@ -244,7 +244,7 @@ boolean MySensor::sendRoute(MyMessage &message) { // This message should be routed back towards sensor net gateway ok = sendWrite(nc.parentNodeId, message); // Add this child to our "routing table" if it not already exist - hw.writeConfigByte(EEPROM_ROUTES_ADDRESS+sender, last); + hw_writeConfig(EEPROM_ROUTES_ADDRESS+sender, last); } } @@ -308,7 +308,7 @@ void MySensor::requestTime(void (* _timeCallback)(unsigned long)) { } boolean MySensor::process() { - hw.watchdogReset(); + hw_watchdogReset(); uint8_t to = 0; if (!radio.available(&to)) return false; @@ -357,7 +357,7 @@ boolean MySensor::process() { if (repeaterMode && last != nc.parentNodeId) { // Message is from one of the child nodes. Add it to routing table. - hw.writeConfigByte(EEPROM_ROUTES_ADDRESS+sender, last); + hw_writeConfig(EEPROM_ROUTES_ADDRESS+sender, last); } // Check if sender requests an ack back. @@ -385,8 +385,8 @@ boolean MySensor::process() { // Found a neighbor closer to GW than previously found nc.distance = distance; nc.parentNodeId = msg.sender; - hw.writeConfigByte(EEPROM_PARENT_NODE_ID_ADDRESS, nc.parentNodeId); - hw.writeConfigByte(EEPROM_DISTANCE_ADDRESS, nc.distance); + hw_writeConfig(EEPROM_PARENT_NODE_ID_ADDRESS, nc.parentNodeId); + hw_writeConfig(EEPROM_DISTANCE_ADDRESS, nc.distance); debug(PSTR("parent=%d, d=%d\n"), nc.parentNodeId, nc.distance); } } @@ -406,7 +406,7 @@ boolean MySensor::process() { CLEAR_SIGN(msg.sender); } // Save updated table - hw.writeConfigBlock((void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, (void*)doSign, sizeof(doSign)); + hw_writeConfigBlock((void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, (void*)doSign, sizeof(doSign)); // Inform sender about our preference if we are a gateway, but only require signing if the sender required signing // We do not currently want a gateway to require signing from all nodes in a network just because it wants one node @@ -425,7 +425,7 @@ boolean MySensor::process() { if (type == I_REBOOT) { // Requires MySensors or other bootloader with watchdogs enabled - hw.reboot(); + hw_reboot(); } else if (type == I_ID_RESPONSE) { if (nc.nodeId == AUTO) { nc.nodeId = msg.getByte(); @@ -436,7 +436,7 @@ boolean MySensor::process() { } setupNode(); // Write id to EEPROM - hw.writeConfigByte(EEPROM_NODE_ID_ADDRESS, nc.nodeId); + hw_writeConfig(EEPROM_NODE_ID_ADDRESS, nc.nodeId); debug(PSTR("id=%d\n"), nc.nodeId); } } else if (type == I_CONFIG) { @@ -444,18 +444,18 @@ boolean MySensor::process() { // and store it in eeprom if changed isMetric = msg.getString()[0] == 'M' ; cc.isMetric = isMetric; - hw.writeConfigByte(EEPROM_CONTROLLER_CONFIG_ADDRESS, isMetric); + hw_writeConfig(EEPROM_CONTROLLER_CONFIG_ADDRESS, isMetric); } else if (type == I_CHILDREN) { if (repeaterMode && msg.getString()[0] == 'C') { // Clears child relay data for this node debug(PSTR("clear\n")); uint8_t i = 255; do { - hw.writeConfigByte(EEPROM_ROUTES_ADDRESS+i, 0xff); + hw_writeConfig(EEPROM_ROUTES_ADDRESS+i, 0xff); } while (i--); // Clear parent node id & distance to gw - hw.writeConfigByte(EEPROM_PARENT_NODE_ID_ADDRESS, 0xFF); - hw.writeConfigByte(EEPROM_DISTANCE_ADDRESS, 0xFF); + hw_writeConfig(EEPROM_PARENT_NODE_ID_ADDRESS, 0xFF); + hw_writeConfig(EEPROM_DISTANCE_ADDRESS, 0xFF); // Find parent node findParentNode(); sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_CHILDREN,false).set("")); @@ -480,7 +480,7 @@ boolean MySensor::process() { // Relaying nodes should always answer ping messages // Wait a random delay of 0-2 seconds to minimize collision // between ping ack messages from other relaying nodes - wait(hw.millisec() & 0x3ff); + wait(hw_millis() & 0x3ff); sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance)); } } else if (to == nc.nodeId) { @@ -496,15 +496,15 @@ MyMessage& MySensor::getLastMessage() { } void MySensor::saveState(uint8_t pos, uint8_t value) { - hw.writeConfigByte(EEPROM_LOCAL_CONFIG_ADDRESS+pos, value); + hw_writeConfig(EEPROM_LOCAL_CONFIG_ADDRESS+pos, value); } uint8_t MySensor::loadState(uint8_t pos) { - return hw.readConfigByte(EEPROM_LOCAL_CONFIG_ADDRESS+pos); + return hw_readConfig(EEPROM_LOCAL_CONFIG_ADDRESS+pos); } void MySensor::wait(unsigned long ms) { - unsigned long enter = hw.millisec(); - while (hw.millisec() - enter < ms) { + unsigned long enter = hw_millis(); + while (hw_millis() - enter < ms) { process(); } } @@ -530,9 +530,9 @@ bool MySensor::sign(MyMessage &message) { } else { // We have to wait for the nonce to arrive before we can sign our original message // Other messages could come in-between. We trust process() takes care of them - unsigned long enter = hw.millisec(); + unsigned long enter = hw_millis(); msgSign = message; // Copy the message to sign since message buffer might be touched in process() - while (hw.millisec() - enter < 5000) { + while (hw_millis() - enter < 5000) { if (process()) { if (mGetCommand(getLastMessage()) == C_INTERNAL && getLastMessage().type == I_GET_NONCE_RESPONSE) { // Proceed with signing if nonce has been received diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index a58d93a..9a2ec57 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -13,14 +13,13 @@ #define MySensor_h #include "Version.h" // Auto generated by bot +#include "MyConfig.h" #include "MyHw.h" -#include "MyHwATMega328.h" #include "MyTransport.h" #include "MyTransportNRF24.h" #include "MyParser.h" #include "MySigning.h" #include "MySigningNone.h" -#include "MyConfig.h" #include "MyMessage.h" #include #include @@ -74,7 +73,7 @@ class MySensor * Creates a new instance of Sensor class. * */ - MySensor(MyTransport &radio =*new MyTransportNRF24(), MySigning &signer=*new MySigningNone(), MyHw &hw=*new MyHwATMega328()); + MySensor(MyTransport &radio =*new MyTransportNRF24(), MySigning &signer=*new MySigningNone(), MyHw &hw=*new MyHwDriver()); /** * Begin operation of the MySensors library From cb5e3172bdbf5e8121284aa203d5f7c694ae0a96 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 16 Mar 2015 19:39:06 +0100 Subject: [PATCH 076/137] Fixed compile problem --- libraries/MySensors/MyHw.h | 2 -- libraries/MySensors/MyHwATMega328.h | 14 +++++++------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/libraries/MySensors/MyHw.h b/libraries/MySensors/MyHw.h index 95cf2a4..b73ec23 100644 --- a/libraries/MySensors/MyHw.h +++ b/libraries/MySensors/MyHw.h @@ -3,9 +3,7 @@ #include #include -#include "MyConfig.h" -//#include "MySensor.h" /** * The Hw contains all hardware specific details of the platform */ diff --git a/libraries/MySensors/MyHwATMega328.h b/libraries/MySensors/MyHwATMega328.h index 618a789..5a63faf 100644 --- a/libraries/MySensors/MyHwATMega328.h +++ b/libraries/MySensors/MyHwATMega328.h @@ -1,7 +1,8 @@ #ifndef MyHwATMega328_h #define MyHwATMega328_h -#include "MyConfig.h" +#include "MyHw.h" +//#include "MyConfig.h" #include "MyMessage.h" #include #include @@ -10,7 +11,6 @@ #include #include -#include "MyHw.h" #ifdef __cplusplus #include @@ -20,12 +20,12 @@ // Define these as macros to save valuable space #define hw_init() Serial.begin(BAUD_RATE) #define hw_watchdogReset() wdt_reset() -#define hw_reboot() wdt_enable(WDTO_15MS); for (;;) +#define hw_reboot() wdt_enable(WDTO_15MS); while (1) #define hw_millis() millis() -#define hw_readConfig(__pos) eeprom_read_byte((uint8_t*)__pos) -#define hw_writeConfig(__pos, __value) eeprom_update_byte((uint8_t*)__pos, __value) -#define hw_readConfigBlock(__buf, __pos, __length) eeprom_read_block(buf, (void*)__pos, __length) -#define hw_writeConfigBlock(__pos, __buf, __length) eeprom_write_block((void*)__pos, (void*)__buf, __length) +#define hw_readConfig(__pos) (eeprom_read_byte((uint8_t*)(__pos))) +#define hw_writeConfig(__pos, __value) (eeprom_update_byte((uint8_t*)(__pos), (__value))) +#define hw_readConfigBlock(__buf, __pos, __length) (eeprom_read_block((__buf), (void*)(__pos), (__length))) +#define hw_writeConfigBlock(__pos, __buf, __length) (eeprom_write_block((void*)(__pos), (void*)__buf, (__length))) From 4c4c9a8b39332516a2196490bb749933e3d1df59 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 7 Mar 2015 14:47:06 +0100 Subject: [PATCH 077/137] Added SHA command to ATSHA204 backend driver The SHA command is available in ATSHA204A variants of the chip and can be used to calculate SHA256 digests of arbitrary data. This enables us to strengthen the quality of the signatures by salting signatures with node-specific data and improving the quality of random data. --- libraries/MySensors/MySigningAtsha204.cpp | 26 +++++++++++++++++++++++ libraries/MySensors/MySigningAtsha204.h | 3 ++- libraries/MySensors/utility/ATSHA204.cpp | 15 +++++++++---- libraries/MySensors/utility/ATSHA204.h | 16 +++++++++++++- 4 files changed, 54 insertions(+), 6 deletions(-) diff --git a/libraries/MySensors/MySigningAtsha204.cpp b/libraries/MySensors/MySigningAtsha204.cpp index 1effefc..146ce30 100644 --- a/libraries/MySensors/MySigningAtsha204.cpp +++ b/libraries/MySensors/MySigningAtsha204.cpp @@ -215,3 +215,29 @@ bool MySigningAtsha204::calculateSignature(MyMessage &msg) { DEBUG_ATSHA_PRINTBUF("HMAC:", &rx_buffer[SHA204_BUFFER_POS_DATA], 32); return true; // We return with the signature in rx_buffer[SHA204_BUFFER_POS_DATA] } + +// Helper to calculate a generic SHA256 digest of provided buffer (returned in rx_buffer[SHA204_BUFFER_POS_DATA]) (only supports one block) +uint8_t* MySigningAtsha204::sha256(const uint8_t* data, size_t sz) { + // Initiate SHA256 calculator + if (atsha204.sha204m_execute(SHA204_SHA, SHA_INIT, 0, 0, NULL, + SHA_COUNT_SHORT, tx_buffer, SHA_RSP_SIZE_SHORT, rx_buffer) != SHA204_SUCCESS) { + DEBUG_ATSHA_PRINTLN("Failed to initiate sha256"); + return NULL; + } + + // Calculate a hash + memset(temp_message, 0x00, SHA_MSG_SIZE); + memcpy(temp_message, data, sz); + temp_message[sz] = 0x80; + // Write length data to the last bytes + temp_message[SHA_MSG_SIZE-2] = (sz >> 5); + temp_message[SHA_MSG_SIZE-1] = (sz << 3); + DEBUG_ATSHA_PRINTBUF("Data to hash (padded):", temp_message, SHA_MSG_SIZE); + if (atsha204.sha204m_execute(SHA204_SHA, SHA_CALC, 0, SHA_MSG_SIZE, temp_message, + SHA_COUNT_LONG, tx_buffer, SHA_RSP_SIZE_LONG, rx_buffer) != SHA204_SUCCESS) { + DEBUG_ATSHA_PRINTLN("Failed to calculate sha256"); + return NULL; + } + DEBUG_ATSHA_PRINTBUF("SHA:", &rx_buffer[SHA204_BUFFER_POS_DATA], 32); + return &rx_buffer[SHA204_BUFFER_POS_DATA]; +} diff --git a/libraries/MySensors/MySigningAtsha204.h b/libraries/MySensors/MySigningAtsha204.h index 8850b2c..d6b3465 100644 --- a/libraries/MySensors/MySigningAtsha204.h +++ b/libraries/MySensors/MySigningAtsha204.h @@ -31,10 +31,11 @@ private: unsigned long timestamp; bool verification_ongoing; uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH]; - uint8_t temp_message[32]; + uint8_t temp_message[SHA_MSG_SIZE]; uint8_t rx_buffer[SHA204_RSP_SIZE_MAX]; uint8_t tx_buffer[SHA204_CMD_SIZE_MAX]; bool calculateSignature(MyMessage &msg); + uint8_t* sha256(const uint8_t* data, size_t sz); }; #endif diff --git a/libraries/MySensors/utility/ATSHA204.cpp b/libraries/MySensors/utility/ATSHA204.cpp index da63668..21ad514 100644 --- a/libraries/MySensors/utility/ATSHA204.cpp +++ b/libraries/MySensors/utility/ATSHA204.cpp @@ -447,12 +447,19 @@ uint8_t atsha204Class::sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t response_size = RANDOM_RSP_SIZE; break; - case SHA204_WRITE: - poll_delay = WRITE_DELAY; - poll_timeout = WRITE_EXEC_MAX - WRITE_DELAY; - response_size = WRITE_RSP_SIZE; + case SHA204_SHA: + poll_delay = SHA_DELAY; + poll_timeout = SHA_EXEC_MAX - SHA_DELAY; + response_size = param1 == SHA_INIT + ? SHA_RSP_SIZE_SHORT : SHA_RSP_SIZE_LONG; break; + case SHA204_WRITE: + poll_delay = WRITE_DELAY; + poll_timeout = WRITE_EXEC_MAX - WRITE_DELAY; + response_size = WRITE_RSP_SIZE; + break; + default: poll_delay = 0; poll_timeout = SHA204_COMMAND_EXEC_MAX; diff --git a/libraries/MySensors/utility/ATSHA204.h b/libraries/MySensors/utility/ATSHA204.h index cb2abc8..c2a057e 100644 --- a/libraries/MySensors/utility/ATSHA204.h +++ b/libraries/MySensors/utility/ATSHA204.h @@ -59,6 +59,7 @@ #define SHA204_HMAC ((uint8_t) 0x11) //!< HMAC command op-code #define SHA204_NONCE ((uint8_t) 0x16) //!< Nonce command op-code #define SHA204_RANDOM ((uint8_t) 0x1B) //!< Random command op-code +#define SHA204_SHA ((uint8_t) 0x47) //!< SHA command op-code #define SHA204_WRITE ((uint8_t) 0x12) //!< Write command op-code // packet size definitions @@ -122,6 +123,15 @@ #define RANDOM_SEED_UPDATE ((uint8_t) 0x00) //!< Random mode for automatic seed update #define RANDOM_NO_SEED_UPDATE ((uint8_t) 0x01) //!< Random mode for no seed update +// SHA command definitions +#define SHA_MODE_IDX SHA204_PARAM1_IDX //!< SHA command index for mode +#define SHA_PARAM2_IDX SHA204_PARAM2_IDX //!< SHA command index for 2. parameter +#define SHA_COUNT_SHORT SHA204_CMD_SIZE_MIN //!< SHA command packet size for init +#define SHA_COUNT_LONG (71) //!< SHA command packet size for calculation +#define SHA_MSG_SIZE (64) //!< SHA message data size +#define SHA_INIT ((uint8_t) 0x00) //!< SHA mode for init +#define SHA_CALC ((uint8_t) 0x01) //!< SHA mode for calculation + // Write command definitions #define WRITE_ZONE_IDX SHA204_PARAM1_IDX //!< Write command index for zone #define WRITE_ADDR_IDX SHA204_PARAM2_IDX //!< Write command index for address @@ -142,6 +152,8 @@ #define NONCE_RSP_SIZE_SHORT SHA204_RSP_SIZE_MIN //!< response size of Nonce command with mode[0:1] = 3 #define NONCE_RSP_SIZE_LONG SHA204_RSP_SIZE_MAX //!< response size of Nonce command #define RANDOM_RSP_SIZE SHA204_RSP_SIZE_MAX //!< response size of Random command +#define SHA_RSP_SIZE_SHORT SHA204_RSP_SIZE_MIN //!< response size of SHA command with mode[0:1] = 0 +#define SHA_RSP_SIZE_LONG SHA204_RSP_SIZE_MAX //!< response size of SHA command #define WRITE_RSP_SIZE SHA204_RSP_SIZE_MIN //!< response size of Write command // command timing definitions for minimum execution times (ms) @@ -149,6 +161,7 @@ #define HMAC_DELAY ((uint8_t) (27.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) #define NONCE_DELAY ((uint8_t) (22.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) #define RANDOM_DELAY ((uint8_t) (11.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define SHA_DELAY ((uint8_t) (11.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) #define WRITE_DELAY ((uint8_t) ( 4.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) // command timing definitions for maximum execution times (ms) @@ -156,6 +169,7 @@ #define HMAC_EXEC_MAX ((uint8_t) (69.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) #define NONCE_EXEC_MAX ((uint8_t) (60.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) #define RANDOM_EXEC_MAX ((uint8_t) (50.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define SHA_EXEC_MAX ((uint8_t) (22.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) #define WRITE_EXEC_MAX ((uint8_t) (42.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) /* from sha204_config.h */ @@ -172,7 +186,7 @@ #define SHA204_COMMAND_EXEC_MAX ((uint8_t) (69.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) //! maximum command delay #define SHA204_CMD_SIZE_MIN ((uint8_t) 7) //! minimum number of bytes in command (from count byte to second CRC byte) -#define SHA204_CMD_SIZE_MAX ((uint8_t) NONCE_COUNT_LONG) //! maximum size of command packet (Nonce) +#define SHA204_CMD_SIZE_MAX ((uint8_t) SHA_COUNT_LONG) //! maximum size of command packet (SHA) #define SHA204_CRC_SIZE ((uint8_t) 2) //! number of CRC bytes #define SHA204_BUFFER_POS_STATUS (1) //! buffer index of status byte in status response #define SHA204_BUFFER_POS_DATA (1) //! buffer index of first data byte in data response From a1024cd2cd8607db078bd2a2391fdf6d575da23f Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Mon, 9 Mar 2015 21:37:16 +0100 Subject: [PATCH 078/137] Added support to read the serial number from ATSHA204 The serial number can be used for whitelisting of nodes that are considered "trusted". --- libraries/MySensors/utility/ATSHA204.cpp | 45 ++++++++++++++++++++++++ libraries/MySensors/utility/ATSHA204.h | 25 +++++++++++++ 2 files changed, 70 insertions(+) diff --git a/libraries/MySensors/utility/ATSHA204.cpp b/libraries/MySensors/utility/ATSHA204.cpp index 21ad514..9991335 100644 --- a/libraries/MySensors/utility/ATSHA204.cpp +++ b/libraries/MySensors/utility/ATSHA204.cpp @@ -18,6 +18,34 @@ atsha204Class::atsha204Class(uint8_t pin) device_port_IN = portInputRegister(port); } +uint8_t atsha204Class::getSerialNumber(uint8_t * response) +{ + uint8_t readCommand[READ_COUNT]; + uint8_t readResponse[READ_4_RSP_SIZE]; + + /* read from bytes 0->3 of config zone */ + uint8_t returnCode = sha204m_read(readCommand, readResponse, SHA204_ZONE_CONFIG, ADDRESS_SN03); + if (!returnCode) // should return 0 if successful + { + for (int i=0; i<4; i++) // store bytes 0-3 into respones array + response[i] = readResponse[SHA204_BUFFER_POS_DATA+i]; + + /* read from bytes 8->11 of config zone */ + returnCode = sha204m_read(readCommand, readResponse, SHA204_ZONE_CONFIG, ADDRESS_SN47); + + for (int i=4; i<8; i++) // store bytes 4-7 of SN into response array + response[i] = readResponse[SHA204_BUFFER_POS_DATA+(i-4)]; + + if (!returnCode) + { /* Finally if last two reads were successful, read byte 8 of the SN */ + returnCode = sha204m_read(readCommand, readResponse, SHA204_ZONE_CONFIG, ADDRESS_SN8); + response[8] = readResponse[SHA204_BUFFER_POS_DATA]; // Byte 8 of SN should always be 0xEE + } + } + + return returnCode; +} + /* SWI bit bang functions */ void atsha204Class::swi_set_signal_pin(uint8_t is_high) @@ -412,6 +440,23 @@ uint8_t atsha204Class::sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_s /* Marshaling functions */ +uint8_t atsha204Class::sha204m_read(uint8_t *tx_buffer, uint8_t *rx_buffer, uint8_t zone, uint16_t address) +{ + uint8_t rx_size; + + address >>= 2; + + tx_buffer[SHA204_COUNT_IDX] = READ_COUNT; + tx_buffer[SHA204_OPCODE_IDX] = SHA204_READ; + tx_buffer[READ_ZONE_IDX] = zone; + tx_buffer[READ_ADDR_IDX] = (uint8_t) (address & SHA204_ADDRESS_MASK); + tx_buffer[READ_ADDR_IDX + 1] = 0; + + rx_size = (zone & SHA204_ZONE_COUNT_FLAG) ? READ_32_RSP_SIZE : READ_4_RSP_SIZE; + + return sha204c_send_and_receive(&tx_buffer[0], rx_size, &rx_buffer[0], READ_DELAY, READ_EXEC_MAX - READ_DELAY); +} + uint8_t atsha204Class::sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t param2, uint8_t datalen1, uint8_t *data1, uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer) { diff --git a/libraries/MySensors/utility/ATSHA204.h b/libraries/MySensors/utility/ATSHA204.h index c2a057e..d29f884 100644 --- a/libraries/MySensors/utility/ATSHA204.h +++ b/libraries/MySensors/utility/ATSHA204.h @@ -59,6 +59,7 @@ #define SHA204_HMAC ((uint8_t) 0x11) //!< HMAC command op-code #define SHA204_NONCE ((uint8_t) 0x16) //!< Nonce command op-code #define SHA204_RANDOM ((uint8_t) 0x1B) //!< Random command op-code +#define SHA204_READ ((uint8_t) 0x02) //!< Read command op-code #define SHA204_SHA ((uint8_t) 0x47) //!< SHA command op-code #define SHA204_WRITE ((uint8_t) 0x12) //!< Write command op-code @@ -123,6 +124,13 @@ #define RANDOM_SEED_UPDATE ((uint8_t) 0x00) //!< Random mode for automatic seed update #define RANDOM_NO_SEED_UPDATE ((uint8_t) 0x01) //!< Random mode for no seed update +// Read command definitions +#define READ_ZONE_IDX SHA204_PARAM1_IDX //!< Read command index for zone +#define READ_ADDR_IDX SHA204_PARAM2_IDX //!< Read command index for address +#define READ_COUNT SHA204_CMD_SIZE_MIN //!< Read command packet size +#define READ_ZONE_MASK ((uint8_t) 0x83) //!< Read zone bits 2 to 6 are 0. +#define READ_ZONE_MODE_32_BYTES ((uint8_t) 0x80) //!< Read mode: 32 bytes + // SHA command definitions #define SHA_MODE_IDX SHA204_PARAM1_IDX //!< SHA command index for mode #define SHA_PARAM2_IDX SHA204_PARAM2_IDX //!< SHA command index for 2. parameter @@ -152,6 +160,8 @@ #define NONCE_RSP_SIZE_SHORT SHA204_RSP_SIZE_MIN //!< response size of Nonce command with mode[0:1] = 3 #define NONCE_RSP_SIZE_LONG SHA204_RSP_SIZE_MAX //!< response size of Nonce command #define RANDOM_RSP_SIZE SHA204_RSP_SIZE_MAX //!< response size of Random command +#define READ_4_RSP_SIZE SHA204_RSP_SIZE_VAL //!< response size of Read command when reading 4 bytes +#define READ_32_RSP_SIZE SHA204_RSP_SIZE_MAX //!< response size of Read command when reading 32 bytes #define SHA_RSP_SIZE_SHORT SHA204_RSP_SIZE_MIN //!< response size of SHA command with mode[0:1] = 0 #define SHA_RSP_SIZE_LONG SHA204_RSP_SIZE_MAX //!< response size of SHA command #define WRITE_RSP_SIZE SHA204_RSP_SIZE_MIN //!< response size of Write command @@ -161,6 +171,7 @@ #define HMAC_DELAY ((uint8_t) (27.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) #define NONCE_DELAY ((uint8_t) (22.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) #define RANDOM_DELAY ((uint8_t) (11.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) +#define READ_DELAY ((uint8_t) ( 0.4 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) #define SHA_DELAY ((uint8_t) (11.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) #define WRITE_DELAY ((uint8_t) ( 4.0 * CPU_CLOCK_DEVIATION_NEGATIVE - 0.5)) @@ -169,6 +180,7 @@ #define HMAC_EXEC_MAX ((uint8_t) (69.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) #define NONCE_EXEC_MAX ((uint8_t) (60.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) #define RANDOM_EXEC_MAX ((uint8_t) (50.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) +#define READ_EXEC_MAX ((uint8_t) ( 4.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) #define SHA_EXEC_MAX ((uint8_t) (22.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) #define WRITE_EXEC_MAX ((uint8_t) (42.0 * CPU_CLOCK_DEVIATION_POSITIVE + 0.5)) @@ -195,6 +207,17 @@ #define SHA204_STATUS_BYTE_EXEC ((uint8_t) 0x0F) //! command execution error #define SHA204_STATUS_BYTE_COMM ((uint8_t) 0xFF) //! communication error +/* EEPROM Addresses */ +/* Configuration Zone */ +#define ADDRESS_SN03 0 // SN[0:3] are bytes 0->3 of configuration zone +#define ADDRESS_RevNum 4 // bytes 4->7 of config zone are RevNum +#define ADDRESS_SN47 8 // SN[4:7] are bytes 8->11 of config zone +#define ADDRESS_SN8 12 // SN[8] is byte 12 of config zone, should be 0xEE +#define ADDRESS_I2CEN 14 // I2C Enable, bit 0 represents I2C enable status +#define ADDRESS_I2CADD 16 // Defines I2C address of SHA204 +#define ADDRESS_OTPMODE 18 // Sets the One-time-programmable mode +#define ADDRESS_SELECTOR 19 // Controls writability of Selector + class atsha204Class { private: @@ -207,6 +230,7 @@ private: uint8_t swi_send_bytes(uint8_t count, uint8_t *buffer); uint8_t swi_send_byte(uint8_t value); uint8_t sha204p_receive_response(uint8_t size, uint8_t *response); + uint8_t sha204m_read(uint8_t *tx_buffer, uint8_t *rx_buffer, uint8_t zone, uint16_t address); public: atsha204Class(uint8_t pin); // Constructor uint8_t sha204c_wakeup(uint8_t *response); @@ -215,6 +239,7 @@ public: uint8_t sha204c_resync(uint8_t size, uint8_t *response); uint8_t sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t param2, uint8_t datalen1, uint8_t *data1, uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer); + uint8_t getSerialNumber(uint8_t *response); }; #endif From e35a01766bc8da7bb7790528e2ae5a48f58a11de Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sun, 8 Mar 2015 21:17:34 +0100 Subject: [PATCH 079/137] Implemented basic whitening of nonce A simple (for performanc reasons) whitening scheme has been implemented for the ATSHA204 backeds that strengthens the nonce "randomness". --- libraries/MySensors/MySigningAtsha204.cpp | 52 +++++++++++++------ libraries/MySensors/MySigningAtsha204Soft.cpp | 17 ++++-- 2 files changed, 47 insertions(+), 22 deletions(-) diff --git a/libraries/MySensors/MySigningAtsha204.cpp b/libraries/MySensors/MySigningAtsha204.cpp index 146ce30..2a966fa 100644 --- a/libraries/MySensors/MySigningAtsha204.cpp +++ b/libraries/MySensors/MySigningAtsha204.cpp @@ -42,31 +42,43 @@ MySigningAtsha204::MySigningAtsha204(bool requestSignatures, uint8_t atshaPin) atsha204(atshaPin), verification_ongoing(false) { - // We set the part of the 32-byte nonce that does not fit into a message to 0xAA - memset(current_nonce, 0xAA, sizeof(current_nonce)); } bool MySigningAtsha204::getNonce(MyMessage &msg) { - // Wake device before starting operations - if (atsha204.sha204c_wakeup(rx_buffer) != SHA204_SUCCESS) { - DEBUG_ATSHA_PRINTLN("Failed to wake device"); - return false; - } - // Generate random number for use as nonce - if (atsha204.sha204m_execute(SHA204_RANDOM, RANDOM_NO_SEED_UPDATE, 0, 0, NULL, - RANDOM_COUNT, tx_buffer, RANDOM_RSP_SIZE, rx_buffer) != SHA204_SUCCESS) { - DEBUG_ATSHA_PRINTLN("Failed to generate nonce"); - return false; + uint8_t* pRnd = NULL; + // We used a basic whitening technique that takes the first byte of a new random value and builds up a 32-byte random value + // This 32-byte random value is then hashed (SHA256) to produce the resulting nonce + for (int i = 0; i < 32; i++) { + // Wake device before starting operations + if (atsha204.sha204c_wakeup(rx_buffer) != SHA204_SUCCESS) { + DEBUG_ATSHA_PRINTLN("Failed to wake device"); + return false; + } + if (atsha204.sha204m_execute(SHA204_RANDOM, RANDOM_NO_SEED_UPDATE, 0, 0, NULL, + RANDOM_COUNT, tx_buffer, RANDOM_RSP_SIZE, rx_buffer) != SHA204_SUCCESS) { + DEBUG_ATSHA_PRINTLN("Failed to generate nonce"); + return false; + } + atsha204.sha204c_sleep(); + current_nonce[i] = rx_buffer[SHA204_BUFFER_POS_DATA]; } - - // We can put the device back to sleep as we will program the nonce once we do the verification + pRnd = sha256(current_nonce, 32); atsha204.sha204c_sleep(); - // Store nonce and replace the first byte in the nonce with our signing identifier - memcpy(current_nonce, &rx_buffer[SHA204_BUFFER_POS_DATA], MAX_PAYLOAD); + if (!pRnd) { + DEBUG_ATSHA_PRINTLN("Failed to hash random value"); + return false; + } + + memcpy(current_nonce, pRnd, MAX_PAYLOAD); + + // We set the part of the 32-byte nonce that does not fit into a message to 0xAA + memset(¤t_nonce[MAX_PAYLOAD], 0xAA, sizeof(current_nonce)-MAX_PAYLOAD); + + // Replace the first byte in the nonce with our signing identifier current_nonce[0] = SIGNING_IDENTIFIER; - + // Transfer the first part of the nonce to the message msg.set(current_nonce, MAX_PAYLOAD); verification_ongoing = true; @@ -218,6 +230,12 @@ bool MySigningAtsha204::calculateSignature(MyMessage &msg) { // Helper to calculate a generic SHA256 digest of provided buffer (returned in rx_buffer[SHA204_BUFFER_POS_DATA]) (only supports one block) uint8_t* MySigningAtsha204::sha256(const uint8_t* data, size_t sz) { + // Wake device before starting operations + if (atsha204.sha204c_wakeup(rx_buffer) != SHA204_SUCCESS) { + DEBUG_ATSHA_PRINTLN("Failed to wake device"); + return NULL; + } + // Initiate SHA256 calculator if (atsha204.sha204m_execute(SHA204_SHA, SHA_INIT, 0, 0, NULL, SHA_COUNT_SHORT, tx_buffer, SHA_RSP_SIZE_SHORT, rx_buffer) != SHA204_SUCCESS) { diff --git a/libraries/MySensors/MySigningAtsha204Soft.cpp b/libraries/MySensors/MySigningAtsha204Soft.cpp index 3ac6f38..465cd93 100644 --- a/libraries/MySensors/MySigningAtsha204Soft.cpp +++ b/libraries/MySensors/MySigningAtsha204Soft.cpp @@ -49,17 +49,24 @@ MySigningAtsha204Soft::MySigningAtsha204Soft(bool requestSignatures, uint8_t ran Sha256() { - // We set the part of the 32-byte nonce that does not fit into a message to 0xAA - memset(current_nonce, 0xAA, sizeof(current_nonce)); } bool MySigningAtsha204Soft::getNonce(MyMessage &msg) { // Set randomseed randomSeed(analogRead(rndPin)); - for (int i = 0; i < MAX_PAYLOAD; i++) - { - current_nonce[i] = random(255); + + // We used a basic whitening technique that takes the first byte of a new random value and builds up a 32-byte random value + // This 32-byte random value is then hashed (SHA256) to produce the resulting nonce + Sha256.init(); + for (int i = 0; i < 32; i++) { + Sha256.write(random(255)); } + memcpy(current_nonce, Sha256.result(), MAX_PAYLOAD); + + // We set the part of the 32-byte nonce that does not fit into a message to 0xAA + memset(¤t_nonce[MAX_PAYLOAD], 0xAA, sizeof(current_nonce)-MAX_PAYLOAD); + + // Replace the first byte in the nonce with our signing identifier current_nonce[0] = SIGNING_IDENTIFIER; // Transfer the first part of the nonce to the message From cf31edcb810ff04b7a9c367d52fb91b07729086a Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Fri, 13 Mar 2015 18:52:47 +0100 Subject: [PATCH 080/137] New way of presenting ATSHA204 serial in personalizer The serial is now more copy+paste friendly for use in whitelists. --- .../Sha204Personalizer/Sha204Personalizer.ino | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino b/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino index 066c834..4b7017f 100644 --- a/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino +++ b/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino @@ -41,7 +41,7 @@ //#define SKIP_KEY_STORAGE // Uncomment this to skip key data storage (once configuration is locked, key -// will aways randomize ) +// will aways randomize) // Uncomment this to skip key generation and use 'user_key_data' as key instead. //#define USER_KEY_DATA @@ -703,6 +703,19 @@ void setup() else { Serial.print(F("Device serial: ")); + Serial.print('{'); + for (int i=0; i<9; i++) + { + Serial.print(F("0x")); + if (rx_buffer[i] < 0x10) + { + Serial.print('0'); // Because Serial.print does not 0-pad HEX + } + Serial.print(rx_buffer[i], HEX); + if (i < 8) Serial.print(','); + } + Serial.print('}'); + Serial.println(); for (int i=0; i<9; i++) { if (rx_buffer[i] < 0x10) From f295ef2961809777247b86471b5438e3fed74611 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Fri, 13 Mar 2015 23:44:12 +0100 Subject: [PATCH 081/137] Whitelisting support in signing backend Whitelisting is enabled using MY_SECURE_NODE_WHITELISTING in MyConfig.h. The whitelist is provided in backend constructors. See the SecureActuator example for a typical usecase. --- libraries/MySensors/MyConfig.h | 12 ++++ libraries/MySensors/MySigningAtsha204.cpp | 68 +++++++++++++------ libraries/MySensors/MySigningAtsha204.h | 19 +++++- libraries/MySensors/MySigningAtsha204Soft.cpp | 53 +++++++++++++-- libraries/MySensors/MySigningAtsha204Soft.h | 21 +++++- .../SecureActuator/SecureActuator.ino | 37 ++++++++-- libraries/MySensors/utility/ATSHA204.h | 2 + 7 files changed, 177 insertions(+), 35 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 0b4d806..e68709a 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -21,11 +21,23 @@ typedef MyHwATMega328 MyHwDriver; // which might vary, especially in networks with many hops. 5s ought to be enough for anyone. #define MY_VERIFICATION_TIMEOUT_MS 5000 +// Enable to turn on whitelisting +// When enabled, a signing node will salt the signature with it's unique signature and nodeId. +// The verifying node will look up the sender in a local table of trusted nodes and +// do the corresponding salting in order to verify the signature. +// For this reason, if whitelisting is enabled on one of the nodes in a sign-verify pair, both +// nodes have to implement whitelisting for this to work. +// Note that a node can still transmit a non-salted message (i.e. have whitelisting disabled) +// to a node that has whitelisting enabled (assuming the receiver does not have a matching entry +// for the sender in it's whitelist) +//#define MY_SECURE_NODE_WHITELISTING + // MySigningAtsha204 default setting #define MY_ATSHA204_PIN 17 // A3 - pin where ATSHA204 is attached // MySigningAtsha204Soft default settings #define MY_RANDOMSEED_PIN 7 // A7 - Pin used for random generation (do not connect anything to this) + // Key to use for HMAC calculation in MySigningAtsha204Soft (32 bytes) #define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 diff --git a/libraries/MySensors/MySigningAtsha204.cpp b/libraries/MySensors/MySigningAtsha204.cpp index 2a966fa..e9fcd42 100644 --- a/libraries/MySensors/MySigningAtsha204.cpp +++ b/libraries/MySensors/MySigningAtsha204.cpp @@ -36,10 +36,18 @@ static void DEBUG_ATSHA_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) #endif -MySigningAtsha204::MySigningAtsha204(bool requestSignatures, uint8_t atshaPin) +MySigningAtsha204::MySigningAtsha204(bool requestSignatures, +#ifdef MY_SECURE_NODE_WHITELISTING + uint8_t nof_whitelist_entries, const whitelist_entry_t* the_whitelist, +#endif + uint8_t atshaPin) : MySigning(requestSignatures), atsha204(atshaPin), +#ifdef MY_SECURE_NODE_WHITELISTING + whitelist(the_whitelist), + whitlist_sz(nof_whitelist_entries), +#endif verification_ongoing(false) { } @@ -50,21 +58,14 @@ bool MySigningAtsha204::getNonce(MyMessage &msg) { // We used a basic whitening technique that takes the first byte of a new random value and builds up a 32-byte random value // This 32-byte random value is then hashed (SHA256) to produce the resulting nonce for (int i = 0; i < 32; i++) { - // Wake device before starting operations - if (atsha204.sha204c_wakeup(rx_buffer) != SHA204_SUCCESS) { - DEBUG_ATSHA_PRINTLN("Failed to wake device"); - return false; - } if (atsha204.sha204m_execute(SHA204_RANDOM, RANDOM_NO_SEED_UPDATE, 0, 0, NULL, RANDOM_COUNT, tx_buffer, RANDOM_RSP_SIZE, rx_buffer) != SHA204_SUCCESS) { DEBUG_ATSHA_PRINTLN("Failed to generate nonce"); return false; } - atsha204.sha204c_sleep(); current_nonce[i] = rx_buffer[SHA204_BUFFER_POS_DATA]; } pRnd = sha256(current_nonce, 32); - atsha204.sha204c_sleep(); if (!pRnd) { DEBUG_ATSHA_PRINTLN("Failed to hash random value"); @@ -134,6 +135,19 @@ bool MySigningAtsha204::signMsg(MyMessage &msg) { return false; } +#ifdef MY_SECURE_NODE_WHITELISTING + // Salt the signature with the senders nodeId and the unique serial of the ATSHA device + memcpy(current_nonce, &rx_buffer[SHA204_BUFFER_POS_DATA], 32); // We can reuse the nonce buffer now since it is no longer needed + current_nonce[32] = msg.sender; + (void)atsha204.getSerialNumber(¤t_nonce[33]); + (void)sha256(current_nonce, 32+1+SHA204_SERIAL_SZ); // we can 'void' sha256 because the hash is already put in the correct place + memset(current_nonce, 0xAA, NONCE_NUMIN_SIZE_PASSTHROUGH); + DEBUG_ATSHA_PRINTLN("Signature salted"); +#endif + + // Overwrite the first byte in the signature with the signing identifier + rx_buffer[SHA204_BUFFER_POS_DATA] = SIGNING_IDENTIFIER; + // Transfer as much signature data as the remaining space in the message permits memcpy(&msg.data[mGetLength(msg)], &rx_buffer[SHA204_BUFFER_POS_DATA], MAX_PAYLOAD-mGetLength(msg)); @@ -166,9 +180,29 @@ bool MySigningAtsha204::verifyMsg(MyMessage &msg) { return false; } +#ifdef MY_SECURE_NODE_WHITELISTING + // Look up the senders nodeId in our whitelist and salt the signature with that data + for (int j=0; j < whitlist_sz; j++) { + if (whitelist[j].nodeId == msg.sender) { + DEBUG_ATSHA_PRINTLN("Sender found in whitelist"); + memcpy(current_nonce, &rx_buffer[SHA204_BUFFER_POS_DATA], 32); // We can reuse the nonce buffer now since it is no longer needed + current_nonce[32] = msg.sender; + memcpy(¤t_nonce[33], whitelist[j].serial, SHA204_SERIAL_SZ); + (void)sha256(current_nonce, 32+1+SHA204_SERIAL_SZ); // we can 'void' sha256 because the hash is already put in the correct place + break; + } + } +#endif + + // Overwrite the first byte in the signature with the signing identifier + rx_buffer[SHA204_BUFFER_POS_DATA] = SIGNING_IDENTIFIER; + // Compare the caluclated signature with the provided signature if (memcmp(&msg.data[mGetLength(msg)], &rx_buffer[SHA204_BUFFER_POS_DATA], MAX_PAYLOAD-mGetLength(msg))) { DEBUG_ATSHA_PRINTBUF("Signature bad. Calculated signature:", &rx_buffer[SHA204_BUFFER_POS_DATA], MAX_PAYLOAD-mGetLength(msg)); +#ifdef MY_SECURE_NODE_WHITELISTING + DEBUG_ATSHA_PRINTLN("Is the sender whitelisted?"); +#endif return false; } else { DEBUG_ATSHA_PRINTLN("Signature ok"); @@ -182,9 +216,6 @@ bool MySigningAtsha204::calculateSignature(MyMessage &msg) { memset(temp_message, 0, 32); memcpy(temp_message, (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); - // Wake device before starting operations - if (atsha204.sha204c_wakeup(rx_buffer) != SHA204_SUCCESS) return false; - // Program the data to sign into the ATSHA204 if (atsha204.sha204m_execute(SHA204_WRITE, SHA204_ZONE_DATA | SHA204_ZONE_COUNT_FLAG, 8 << 3, 32, temp_message, WRITE_COUNT_LONG, tx_buffer, WRITE_RSP_SIZE, rx_buffer) != SHA204_SUCCESS) { @@ -221,21 +252,12 @@ bool MySigningAtsha204::calculateSignature(MyMessage &msg) { // Put device back to sleep atsha204.sha204c_sleep(); - // Overwrite the first byte in the signature with the signing identifier - rx_buffer[SHA204_BUFFER_POS_DATA] = SIGNING_IDENTIFIER; - DEBUG_ATSHA_PRINTBUF("HMAC:", &rx_buffer[SHA204_BUFFER_POS_DATA], 32); return true; // We return with the signature in rx_buffer[SHA204_BUFFER_POS_DATA] } // Helper to calculate a generic SHA256 digest of provided buffer (returned in rx_buffer[SHA204_BUFFER_POS_DATA]) (only supports one block) uint8_t* MySigningAtsha204::sha256(const uint8_t* data, size_t sz) { - // Wake device before starting operations - if (atsha204.sha204c_wakeup(rx_buffer) != SHA204_SUCCESS) { - DEBUG_ATSHA_PRINTLN("Failed to wake device"); - return NULL; - } - // Initiate SHA256 calculator if (atsha204.sha204m_execute(SHA204_SHA, SHA_INIT, 0, 0, NULL, SHA_COUNT_SHORT, tx_buffer, SHA_RSP_SIZE_SHORT, rx_buffer) != SHA204_SUCCESS) { @@ -250,12 +272,16 @@ uint8_t* MySigningAtsha204::sha256(const uint8_t* data, size_t sz) { // Write length data to the last bytes temp_message[SHA_MSG_SIZE-2] = (sz >> 5); temp_message[SHA_MSG_SIZE-1] = (sz << 3); - DEBUG_ATSHA_PRINTBUF("Data to hash (padded):", temp_message, SHA_MSG_SIZE); + DEBUG_ATSHA_PRINTBUF("Data to hash:", temp_message, SHA_MSG_SIZE); if (atsha204.sha204m_execute(SHA204_SHA, SHA_CALC, 0, SHA_MSG_SIZE, temp_message, SHA_COUNT_LONG, tx_buffer, SHA_RSP_SIZE_LONG, rx_buffer) != SHA204_SUCCESS) { DEBUG_ATSHA_PRINTLN("Failed to calculate sha256"); return NULL; } + + // Put device back to sleep + atsha204.sha204c_sleep(); + DEBUG_ATSHA_PRINTBUF("SHA:", &rx_buffer[SHA204_BUFFER_POS_DATA], 32); return &rx_buffer[SHA204_BUFFER_POS_DATA]; } diff --git a/libraries/MySensors/MySigningAtsha204.h b/libraries/MySensors/MySigningAtsha204.h index d6b3465..b96386a 100644 --- a/libraries/MySensors/MySigningAtsha204.h +++ b/libraries/MySensors/MySigningAtsha204.h @@ -14,13 +14,24 @@ #define SIGNING_IDENTIFIER (1) +#ifdef MY_SECURE_NODE_WHITELISTING +typedef struct { + uint8_t nodeId; + uint8_t serial[SHA204_SERIAL_SZ]; +} whitelist_entry_t; +#endif + // The ATSHA204 is capable of generating proper random numbers for nonce // and can calculate HMAC-SHA256 signatures. This is enterprise- // level of security and ought to implement the signing needs for anybody. class MySigningAtsha204 : public MySigning { public: - MySigningAtsha204(bool requestSignatures=true, uint8_t atshaPin = MY_ATSHA204_PIN); + MySigningAtsha204(bool requestSignatures=true, +#ifdef MY_SECURE_NODE_WHITELISTING + uint8_t nof_whitelist_entries=0, const whitelist_entry_t* the_whitelist=NULL, +#endif + uint8_t atshaPin=MY_ATSHA204_PIN); bool getNonce(MyMessage &msg); bool checkTimer(void); bool putNonce(MyMessage &msg); @@ -30,12 +41,16 @@ private: atsha204Class atsha204; unsigned long timestamp; bool verification_ongoing; - uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH]; + uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH+SHA204_SERIAL_SZ+1]; uint8_t temp_message[SHA_MSG_SIZE]; uint8_t rx_buffer[SHA204_RSP_SIZE_MAX]; uint8_t tx_buffer[SHA204_CMD_SIZE_MAX]; bool calculateSignature(MyMessage &msg); uint8_t* sha256(const uint8_t* data, size_t sz); +#ifdef MY_SECURE_NODE_WHITELISTING + uint8_t whitlist_sz; + const whitelist_entry_t* whitelist; +#endif }; #endif diff --git a/libraries/MySensors/MySigningAtsha204Soft.cpp b/libraries/MySensors/MySigningAtsha204Soft.cpp index 465cd93..4d56cf1 100644 --- a/libraries/MySensors/MySigningAtsha204Soft.cpp +++ b/libraries/MySensors/MySigningAtsha204Soft.cpp @@ -40,11 +40,21 @@ static void DEBUG_ATSHASOFT_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) #define DEBUG_ATSHASOFT_PRINTBUF(str, buf, sz) #endif -MySigningAtsha204Soft::MySigningAtsha204Soft(bool requestSignatures, uint8_t randomseedPin) +MySigningAtsha204Soft::MySigningAtsha204Soft(bool requestSignatures, +#ifdef MY_SECURE_NODE_WHITELISTING + uint8_t nof_whitelist_entries, const whitelist_entry_t* the_whitelist, + const uint8_t* the_serial, +#endif + uint8_t randomseedPin) : MySigning(requestSignatures), rndPin(randomseedPin), hmacKey({MY_HMAC_KEY}), +#ifdef MY_SECURE_NODE_WHITELISTING + whitlist_sz(nof_whitelist_entries), + whitelist(the_whitelist), + node_serial_info(the_serial), +#endif verification_ongoing(false), Sha256() @@ -124,6 +134,19 @@ bool MySigningAtsha204Soft::signMsg(MyMessage &msg) { return false; } +#ifdef MY_SECURE_NODE_WHITELISTING + // Salt the signature with the senders nodeId and the (hopefully) unique serial The Creator has provided + Sha256.init(); + for (int i=0; i<32; i++) Sha256.write(hmac[i]); + Sha256.write(msg.sender); + for (int i=0; i +#define USE_SOFTWARE_ATSHA // Disable to use ATSHA204A circuit + #include +#include #include #include +#ifdef USE_SOFTWARE_ATSHA +#include +#else +#include +#endif #define LOCK_1 3 // Arduino Digital I/O pin number for first lock (second on pin+1 etc) #define NOF_LOCKS 1 // Total number of attached locks @@ -12,13 +19,35 @@ #define LOCK_UNLOCK 0 // GPIO value to write to unlock attached lock MyTransportNRF24 radio; // NRFRF24L01 radio driver +MyHwATMega328 hw; // Select AtMega328 hardware profile +#ifdef MY_SECURE_NODE_WHITELISTING +#ifdef USE_SOFTWARE_ATSHA +// Change the soft_serial value to an arbitrary value for proper security +uint8_t soft_serial[SHA204_SERIAL_SZ] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09}; +#endif +// We only use one whitelist entry (the gateway) +whitelist_entry_t node_whitelist[] = { + { .nodeId = GATEWAY_ADDRESS, + .serial = {0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01} } +}; +#ifdef USE_SOFTWARE_ATSHA MySigningAtsha204Soft signer; // Message signing driver -MySensor gw(radio, signer); +#else +MySigningAtsha204 signer(true, 1, node_whitelist); +#endif +#else +#ifdef USE_SOFTWARE_ATSHA +MySigningAtsha204Soft signer; +#else +MySigningAtsha204 signer; +#endif +#endif +MySensor gw(radio, hw, signer); void setup() -{ +{ // Initialize library and add callback for incoming messages (signing is required) - gw.begin(incomingMessage, AUTO, true, AUTO); + gw.begin(incomingMessage, AUTO); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Secure Lock", "1.0"); diff --git a/libraries/MySensors/utility/ATSHA204.h b/libraries/MySensors/utility/ATSHA204.h index d29f884..f4499b4 100644 --- a/libraries/MySensors/utility/ATSHA204.h +++ b/libraries/MySensors/utility/ATSHA204.h @@ -218,6 +218,8 @@ #define ADDRESS_OTPMODE 18 // Sets the One-time-programmable mode #define ADDRESS_SELECTOR 19 // Controls writability of Selector +#define SHA204_SERIAL_SZ 9 // The number of bytes the serial number consists of + class atsha204Class { private: From 611ba0cf442d7d30c40fbf261335280ee5891593 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 14 Mar 2015 12:20:02 +0100 Subject: [PATCH 082/137] Slimmed down memory footprint of signing backends --- libraries/MySensors/MySigningAtsha204.cpp | 136 ++++++------------ libraries/MySensors/MySigningAtsha204.h | 2 +- libraries/MySensors/MySigningAtsha204Soft.cpp | 62 ++++---- libraries/MySensors/MySigningAtsha204Soft.h | 2 +- libraries/MySensors/MySigningNone.cpp | 15 +- libraries/MySensors/utility/ATSHA204.cpp | 12 +- libraries/MySensors/utility/ATSHA204.h | 10 +- 7 files changed, 92 insertions(+), 147 deletions(-) diff --git a/libraries/MySensors/MySigningAtsha204.cpp b/libraries/MySensors/MySigningAtsha204.cpp index e9fcd42..07dca5f 100644 --- a/libraries/MySensors/MySigningAtsha204.cpp +++ b/libraries/MySensors/MySigningAtsha204.cpp @@ -8,18 +8,17 @@ #include "MySigningAtsha204.h" // Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) -//#define DEBUG_ATSHA_SIGNING +//#define DEBUG_SIGNING -#ifdef DEBUG_ATSHA_SIGNING -#define DEBUG_ATSHA_PRINTLN(args) Serial.println(args) +#ifdef DEBUG_SIGNING +#define DEBUG_SIGNING_PRINTLN(args) Serial.println(args) #else -#define DEBUG_ATSHA_PRINTLN(args) +#define DEBUG_SIGNING_PRINTLN(args) #endif -#ifdef DEBUG_ATSHA_SIGNING -static void DEBUG_ATSHA_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) +#ifdef DEBUG_SIGNING +static void DEBUG_SIGNING_PRINTBUF(const __FlashStringHelper* str, uint8_t* buf, uint8_t sz) { - int i; Serial.println(str); for (int i=0; i timestamp + MY_VERIFICATION_TIMEOUT_MS) { - DEBUG_ATSHA_PRINTLN("Verification timeout"); + DEBUG_SIGNING_PRINTLN(F("VT")); // VT = Verification timeout // Purge nonce - memset(current_nonce, 0xAA, NONCE_NUMIN_SIZE_PASSTHROUGH); + memset(current_nonce, 0x00, NONCE_NUMIN_SIZE_PASSTHROUGH); verification_ongoing = false; return false; } @@ -105,44 +96,35 @@ bool MySigningAtsha204::checkTimer() { } bool MySigningAtsha204::putNonce(MyMessage &msg) { - if (mGetLength(msg) != MAX_PAYLOAD) { - DEBUG_ATSHA_PRINTLN("Incoming nonce with incorrect size"); - return false; // We require as big nonce as possible - } - if (((uint8_t*)msg.getCustom())[0] != SIGNING_IDENTIFIER) { - DEBUG_ATSHA_PRINTLN("Incorrect signing identifier"); + DEBUG_SIGNING_PRINTLN(F("ISI")); // ISI = Incorrect signing identifier return false; } memcpy(current_nonce, (uint8_t*)msg.getCustom(), MAX_PAYLOAD); + // We set the part of the 32-byte nonce that does not fit into a message to 0xAA + memset(¤t_nonce[MAX_PAYLOAD], 0xAA, sizeof(current_nonce)-MAX_PAYLOAD); return true; } bool MySigningAtsha204::signMsg(MyMessage &msg) { // If we cannot fit any signature in the message, refuse to sign it if (mGetLength(msg) > MAX_PAYLOAD-2) { - DEBUG_ATSHA_PRINTLN("Cannot fit any signature to this message"); + DEBUG_SIGNING_PRINTLN(F("MTOL")); // Message too large for signature to fit return false; } // Calculate signature of message mSetSigned(msg, 1); // make sure signing flag is set before signature is calculated - DEBUG_ATSHA_PRINTBUF("Message to sign:", (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); - if (!calculateSignature(msg)) { - DEBUG_ATSHA_PRINTLN("Failed to calculate signature"); - mSetSigned(msg, 0); // make sure signing flag is truthful - return false; - } + calculateSignature(msg); #ifdef MY_SECURE_NODE_WHITELISTING // Salt the signature with the senders nodeId and the unique serial of the ATSHA device memcpy(current_nonce, &rx_buffer[SHA204_BUFFER_POS_DATA], 32); // We can reuse the nonce buffer now since it is no longer needed current_nonce[32] = msg.sender; - (void)atsha204.getSerialNumber(¤t_nonce[33]); + atsha204.getSerialNumber(¤t_nonce[33]); (void)sha256(current_nonce, 32+1+SHA204_SERIAL_SZ); // we can 'void' sha256 because the hash is already put in the correct place - memset(current_nonce, 0xAA, NONCE_NUMIN_SIZE_PASSTHROUGH); - DEBUG_ATSHA_PRINTLN("Signature salted"); + DEBUG_SIGNING_PRINTLN(F("SWS")); // SWS = Signature whitelist salted #endif // Overwrite the first byte in the signature with the signing identifier @@ -156,7 +138,7 @@ bool MySigningAtsha204::signMsg(MyMessage &msg) { bool MySigningAtsha204::verifyMsg(MyMessage &msg) { if (!verification_ongoing) { - DEBUG_ATSHA_PRINTLN("No active verification session"); + DEBUG_SIGNING_PRINTLN(F("NAVS")); // NAVS = No active verification session return false; } else { // Make sure we have not expired @@ -167,24 +149,18 @@ bool MySigningAtsha204::verifyMsg(MyMessage &msg) { verification_ongoing = false; if (msg.data[mGetLength(msg)] != SIGNING_IDENTIFIER) { - DEBUG_ATSHA_PRINTLN("Incorrect signing identifier"); + DEBUG_SIGNING_PRINTLN(F("ISI")); // ISI = Incorrect signing identifier return false; } - DEBUG_ATSHA_PRINTBUF("Message to verify:", (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); - DEBUG_ATSHA_PRINTBUF("Signature in message:", (uint8_t*)&msg.data[mGetLength(msg)], MAX_PAYLOAD-mGetLength(msg)); - - // Get signature of message - if (!calculateSignature(msg)) { - DEBUG_ATSHA_PRINTLN("Failed to calculate signature"); - return false; - } + DEBUG_SIGNING_PRINTBUF(F("SIM:"), (uint8_t*)&msg.data[mGetLength(msg)], MAX_PAYLOAD-mGetLength(msg)); // SIM = Signature in message + calculateSignature(msg); // Get signature of message #ifdef MY_SECURE_NODE_WHITELISTING // Look up the senders nodeId in our whitelist and salt the signature with that data for (int j=0; j < whitlist_sz; j++) { if (whitelist[j].nodeId == msg.sender) { - DEBUG_ATSHA_PRINTLN("Sender found in whitelist"); + DEBUG_SIGNING_PRINTLN(F("SIW")); // SIW = Sender found in whitelist memcpy(current_nonce, &rx_buffer[SHA204_BUFFER_POS_DATA], 32); // We can reuse the nonce buffer now since it is no longer needed current_nonce[32] = msg.sender; memcpy(¤t_nonce[33], whitelist[j].serial, SHA204_SERIAL_SZ); @@ -199,71 +175,56 @@ bool MySigningAtsha204::verifyMsg(MyMessage &msg) { // Compare the caluclated signature with the provided signature if (memcmp(&msg.data[mGetLength(msg)], &rx_buffer[SHA204_BUFFER_POS_DATA], MAX_PAYLOAD-mGetLength(msg))) { - DEBUG_ATSHA_PRINTBUF("Signature bad. Calculated signature:", &rx_buffer[SHA204_BUFFER_POS_DATA], MAX_PAYLOAD-mGetLength(msg)); + DEBUG_SIGNING_PRINTBUF(F("SNOK:"), &rx_buffer[SHA204_BUFFER_POS_DATA], MAX_PAYLOAD-mGetLength(msg)); // SNOK = Signature bad #ifdef MY_SECURE_NODE_WHITELISTING - DEBUG_ATSHA_PRINTLN("Is the sender whitelisted?"); + DEBUG_SIGNING_PRINTLN(F("W?")); // W? = Is the sender whitelisted? #endif return false; } else { - DEBUG_ATSHA_PRINTLN("Signature ok"); + DEBUG_SIGNING_PRINTLN(F("SOK")); // SOK = Signature OK return true; } } } // Helper to calculate signature of msg (returned in rx_buffer[SHA204_BUFFER_POS_DATA]) -bool MySigningAtsha204::calculateSignature(MyMessage &msg) { +void MySigningAtsha204::calculateSignature(MyMessage &msg) { memset(temp_message, 0, 32); memcpy(temp_message, (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); // Program the data to sign into the ATSHA204 - if (atsha204.sha204m_execute(SHA204_WRITE, SHA204_ZONE_DATA | SHA204_ZONE_COUNT_FLAG, 8 << 3, 32, temp_message, - WRITE_COUNT_LONG, tx_buffer, WRITE_RSP_SIZE, rx_buffer) != SHA204_SUCCESS) { - DEBUG_ATSHA_PRINTLN("Failed to program data"); - return false; - } + DEBUG_SIGNING_PRINTBUF(F("MSG:"), (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); // MSG = Message to sign + DEBUG_SIGNING_PRINTBUF(F("CNC:"), current_nonce, 32); // CNC = Current nonce + (void)atsha204.sha204m_execute(SHA204_WRITE, SHA204_ZONE_DATA | SHA204_ZONE_COUNT_FLAG, 8 << 3, 32, temp_message, + WRITE_COUNT_LONG, tx_buffer, WRITE_RSP_SIZE, rx_buffer); // Program the nonce to use for the signature (has to be done just before GENDIG due to chip limitations) - if (atsha204.sha204m_execute(SHA204_NONCE, NONCE_MODE_PASSTHROUGH, 0, NONCE_NUMIN_SIZE_PASSTHROUGH, current_nonce, - NONCE_COUNT_LONG, tx_buffer, NONCE_RSP_SIZE_SHORT, rx_buffer) != SHA204_SUCCESS) { - DEBUG_ATSHA_PRINTLN("Failed to program nonce"); - // Purge nonce when used - memset(current_nonce, 0xAA, NONCE_NUMIN_SIZE_PASSTHROUGH); - return false; - } + (void)atsha204.sha204m_execute(SHA204_NONCE, NONCE_MODE_PASSTHROUGH, 0, NONCE_NUMIN_SIZE_PASSTHROUGH, current_nonce, + NONCE_COUNT_LONG, tx_buffer, NONCE_RSP_SIZE_SHORT, rx_buffer); // Purge nonce when used - memset(current_nonce, 0xAA, NONCE_NUMIN_SIZE_PASSTHROUGH); + memset(current_nonce, 0x00, NONCE_NUMIN_SIZE_PASSTHROUGH); // Generate digest of data and nonce - if (atsha204.sha204m_execute(SHA204_GENDIG, GENDIG_ZONE_DATA, 8, 0, NULL, - GENDIG_COUNT_DATA, tx_buffer, GENDIG_RSP_SIZE, rx_buffer) != SHA204_SUCCESS) { - DEBUG_ATSHA_PRINTLN("Failed to generate digest"); - return false; - } + (void)atsha204.sha204m_execute(SHA204_GENDIG, GENDIG_ZONE_DATA, 8, 0, NULL, + GENDIG_COUNT_DATA, tx_buffer, GENDIG_RSP_SIZE, rx_buffer); // Calculate HMAC of message+nonce digest and secret key - if (atsha204.sha204m_execute(SHA204_HMAC, HMAC_MODE_SOURCE_FLAG_MATCH, 0, 0, NULL, - HMAC_COUNT, tx_buffer, HMAC_RSP_SIZE, rx_buffer) != SHA204_SUCCESS) { - DEBUG_ATSHA_PRINTLN("Failed to generate HMAC"); - return false; - } + (void)atsha204.sha204m_execute(SHA204_HMAC, HMAC_MODE_SOURCE_FLAG_MATCH, 0, 0, NULL, + HMAC_COUNT, tx_buffer, HMAC_RSP_SIZE, rx_buffer); // Put device back to sleep atsha204.sha204c_sleep(); - DEBUG_ATSHA_PRINTBUF("HMAC:", &rx_buffer[SHA204_BUFFER_POS_DATA], 32); - return true; // We return with the signature in rx_buffer[SHA204_BUFFER_POS_DATA] + DEBUG_SIGNING_PRINTBUF(F("HMAC:"), &rx_buffer[SHA204_BUFFER_POS_DATA], 32); } -// Helper to calculate a generic SHA256 digest of provided buffer (returned in rx_buffer[SHA204_BUFFER_POS_DATA]) (only supports one block) +// Helper to calculate a generic SHA256 digest of provided buffer (only supports one block) +// The pointer to the hash is returned, but the hash is also stored in rx_buffer[SHA204_BUFFER_POS_DATA]) uint8_t* MySigningAtsha204::sha256(const uint8_t* data, size_t sz) { // Initiate SHA256 calculator - if (atsha204.sha204m_execute(SHA204_SHA, SHA_INIT, 0, 0, NULL, - SHA_COUNT_SHORT, tx_buffer, SHA_RSP_SIZE_SHORT, rx_buffer) != SHA204_SUCCESS) { - DEBUG_ATSHA_PRINTLN("Failed to initiate sha256"); - return NULL; - } + (void)atsha204.sha204m_execute(SHA204_SHA, SHA_INIT, 0, 0, NULL, + SHA_COUNT_SHORT, tx_buffer, SHA_RSP_SIZE_SHORT, rx_buffer); // Calculate a hash memset(temp_message, 0x00, SHA_MSG_SIZE); @@ -272,16 +233,13 @@ uint8_t* MySigningAtsha204::sha256(const uint8_t* data, size_t sz) { // Write length data to the last bytes temp_message[SHA_MSG_SIZE-2] = (sz >> 5); temp_message[SHA_MSG_SIZE-1] = (sz << 3); - DEBUG_ATSHA_PRINTBUF("Data to hash:", temp_message, SHA_MSG_SIZE); - if (atsha204.sha204m_execute(SHA204_SHA, SHA_CALC, 0, SHA_MSG_SIZE, temp_message, - SHA_COUNT_LONG, tx_buffer, SHA_RSP_SIZE_LONG, rx_buffer) != SHA204_SUCCESS) { - DEBUG_ATSHA_PRINTLN("Failed to calculate sha256"); - return NULL; - } + DEBUG_SIGNING_PRINTBUF(F("DTH:"), temp_message, SHA_MSG_SIZE); // DTH = Data to hash + (void)atsha204.sha204m_execute(SHA204_SHA, SHA_CALC, 0, SHA_MSG_SIZE, temp_message, + SHA_COUNT_LONG, tx_buffer, SHA_RSP_SIZE_LONG, rx_buffer); // Put device back to sleep atsha204.sha204c_sleep(); - DEBUG_ATSHA_PRINTBUF("SHA:", &rx_buffer[SHA204_BUFFER_POS_DATA], 32); + DEBUG_SIGNING_PRINTBUF(F("SHA:"), &rx_buffer[SHA204_BUFFER_POS_DATA], 32); return &rx_buffer[SHA204_BUFFER_POS_DATA]; } diff --git a/libraries/MySensors/MySigningAtsha204.h b/libraries/MySensors/MySigningAtsha204.h index b96386a..1ebf386 100644 --- a/libraries/MySensors/MySigningAtsha204.h +++ b/libraries/MySensors/MySigningAtsha204.h @@ -45,7 +45,7 @@ private: uint8_t temp_message[SHA_MSG_SIZE]; uint8_t rx_buffer[SHA204_RSP_SIZE_MAX]; uint8_t tx_buffer[SHA204_CMD_SIZE_MAX]; - bool calculateSignature(MyMessage &msg); + void calculateSignature(MyMessage &msg); uint8_t* sha256(const uint8_t* data, size_t sz); #ifdef MY_SECURE_NODE_WHITELISTING uint8_t whitlist_sz; diff --git a/libraries/MySensors/MySigningAtsha204Soft.cpp b/libraries/MySensors/MySigningAtsha204Soft.cpp index 4d56cf1..d5aa8aa 100644 --- a/libraries/MySensors/MySigningAtsha204Soft.cpp +++ b/libraries/MySensors/MySigningAtsha204Soft.cpp @@ -13,16 +13,16 @@ #include "utility/sha256.h" // Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) -//#define DEBUG_ATSHASOFT_SIGNING +//#define DEBUG_SIGNING -#ifdef DEBUG_ATSHASOFT_SIGNING -#define DEBUG_ATSHASOFT_PRINTLN(args) Serial.println(args) +#ifdef DEBUG_SIGNING +#define DEBUG_SIGNING_PRINTLN(args) Serial.println(args) #else -#define DEBUG_ATSHASOFT_PRINTLN(args) +#define DEBUG_SIGNING_PRINTLN(args) #endif -#ifdef DEBUG_ATSHASOFT_SIGNING -static void DEBUG_ATSHASOFT_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) +#ifdef DEBUG_SIGNING +static void DEBUG_SIGNING_PRINTBUF(const __FlashStringHelper* str, uint8_t* buf, uint8_t sz) { int i; Serial.println(str); @@ -37,7 +37,7 @@ static void DEBUG_ATSHASOFT_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) Serial.println(); } #else -#define DEBUG_ATSHASOFT_PRINTBUF(str, buf, sz) +#define DEBUG_SIGNING_PRINTBUF(str, buf, sz) #endif MySigningAtsha204Soft::MySigningAtsha204Soft(bool requestSignatures, @@ -93,7 +93,7 @@ bool MySigningAtsha204Soft::getNonce(MyMessage &msg) { bool MySigningAtsha204Soft::checkTimer() { if (verification_ongoing) { if (millis() < timestamp || millis() > timestamp + MY_VERIFICATION_TIMEOUT_MS) { - DEBUG_ATSHASOFT_PRINTLN("Verification timeout"); + DEBUG_SIGNING_PRINTLN(F("VT")); // VT = Verification timeout // Purge nonce memset(current_nonce, 0xAA, 32); verification_ongoing = false; @@ -104,13 +104,8 @@ bool MySigningAtsha204Soft::checkTimer() { } bool MySigningAtsha204Soft::putNonce(MyMessage &msg) { - if (mGetLength(msg) != MAX_PAYLOAD) { - DEBUG_ATSHASOFT_PRINTLN("Incoming nonce with incorrect size"); - return false; // We require as big nonce as possible - } - if (((uint8_t*)msg.getCustom())[0] != SIGNING_IDENTIFIER) { - DEBUG_ATSHASOFT_PRINTLN("Incorrect signing identifier"); + DEBUG_SIGNING_PRINTLN(F("ISI")); // ISI = Incorrect signing identifier return false; } @@ -121,18 +116,13 @@ bool MySigningAtsha204Soft::putNonce(MyMessage &msg) { bool MySigningAtsha204Soft::signMsg(MyMessage &msg) { // If we cannot fit any signature in the message, refuse to sign it if (mGetLength(msg) > MAX_PAYLOAD-2) { - DEBUG_ATSHASOFT_PRINTLN("Cannot fit any signature to this message"); + DEBUG_SIGNING_PRINTLN(F("MTOL")); // Message too large for signature to fit return false; } // Calculate signature of message mSetSigned(msg, 1); // make sure signing flag is set before signature is calculated - DEBUG_ATSHASOFT_PRINTBUF("Message to sign:", (uint8_t*)&msg.data[1-HEADER_SIZE], MAX_MESSAGE_LENGTH-1-(MAX_PAYLOAD-mGetLength(msg))); - if (!calculateSignature(msg)) { - DEBUG_ATSHASOFT_PRINTLN("Failed to calculate signature"); - mSetSigned(msg, 0); // make sure signing flag is truthful - return false; - } + calculateSignature(msg); #ifdef MY_SECURE_NODE_WHITELISTING // Salt the signature with the senders nodeId and the (hopefully) unique serial The Creator has provided @@ -141,7 +131,7 @@ bool MySigningAtsha204Soft::signMsg(MyMessage &msg) { Sha256.write(msg.sender); for (int i=0; i */ +#include "MyConfig.h" #include "MySigning.h" #include "MySigningNone.h" // Uncomment this to get some useful serial debug info (Serial.print and Serial.println expected) -//#define DEBUG_NONE_SIGNING +//#define DEBUG_SIGNING -#ifdef DEBUG_NONE_SIGNING -#define DEBUG_NONE_PRINTLN(args) Serial.println(args) +#ifdef DEBUG_SIGNING +#define DEBUG_SIGNING_PRINTLN(args) Serial.println(args) #else -#define DEBUG_NONE_PRINTLN(args) +#define DEBUG_SIGNING_PRINTLN(args) #endif -#ifdef DEBUG_NONE_SIGNING -static void DEBUG_NONE_PRINTBUF(char* str, uint8_t* buf, uint8_t sz) +#ifdef DEBUG_SIGNING +static void DEBUG_NONE_PRINTBUF(const __FlashStringHelper* str, uint8_t* buf, uint8_t sz) { int i; Serial.println(str); @@ -52,7 +53,7 @@ bool MySigningNone::putNonce(MyMessage &msg) { bool MySigningNone::signMsg(MyMessage &msg) { // If we cannot fit any signature in the message, refuse to sign it if (mGetLength(msg) > MAX_PAYLOAD-2) { - DEBUG_NONE_PRINTLN("Cannot fit any signature to this message"); + DEBUG_SIGNING_PRINTLN(F("MTOL")); // Message too large for signature to fit return false; } mSetSigned(msg, 1); // make sure signing flag is set before signature is calculated diff --git a/libraries/MySensors/utility/ATSHA204.cpp b/libraries/MySensors/utility/ATSHA204.cpp index 9991335..c03ae7c 100644 --- a/libraries/MySensors/utility/ATSHA204.cpp +++ b/libraries/MySensors/utility/ATSHA204.cpp @@ -18,14 +18,14 @@ atsha204Class::atsha204Class(uint8_t pin) device_port_IN = portInputRegister(port); } -uint8_t atsha204Class::getSerialNumber(uint8_t * response) +void atsha204Class::getSerialNumber(uint8_t * response) { uint8_t readCommand[READ_COUNT]; uint8_t readResponse[READ_4_RSP_SIZE]; /* read from bytes 0->3 of config zone */ uint8_t returnCode = sha204m_read(readCommand, readResponse, SHA204_ZONE_CONFIG, ADDRESS_SN03); - if (!returnCode) // should return 0 if successful + if (!returnCode) { for (int i=0; i<4; i++) // store bytes 0-3 into respones array response[i] = readResponse[SHA204_BUFFER_POS_DATA+i]; @@ -43,7 +43,7 @@ uint8_t atsha204Class::getSerialNumber(uint8_t * response) } } - return returnCode; + return; } /* SWI bit bang functions */ @@ -212,9 +212,9 @@ uint8_t atsha204Class::swi_receive_bytes(uint8_t count, uint8_t *buffer) /* Physical functions */ -uint8_t atsha204Class::sha204c_sleep() +void atsha204Class::sha204c_sleep() { - return swi_send_byte(SHA204_SWI_FLAG_SLEEP); + swi_send_byte(SHA204_SWI_FLAG_SLEEP); } uint8_t atsha204Class::sha204p_receive_response(uint8_t size, uint8_t *response) @@ -289,7 +289,7 @@ uint8_t atsha204Class::sha204c_resync(uint8_t size, uint8_t *response) // We lost communication. Send a Wake pulse and try // to receive a response (steps 2 and 3 of the // re-synchronization process). - (void) sha204c_sleep(); + sha204c_sleep(); ret_code = sha204c_wakeup(response); // Translate a return value of success into one diff --git a/libraries/MySensors/utility/ATSHA204.h b/libraries/MySensors/utility/ATSHA204.h index f4499b4..3864289 100644 --- a/libraries/MySensors/utility/ATSHA204.h +++ b/libraries/MySensors/utility/ATSHA204.h @@ -233,15 +233,15 @@ private: uint8_t swi_send_byte(uint8_t value); uint8_t sha204p_receive_response(uint8_t size, uint8_t *response); uint8_t sha204m_read(uint8_t *tx_buffer, uint8_t *rx_buffer, uint8_t zone, uint16_t address); + uint8_t sha204c_wakeup(uint8_t *response); + uint8_t sha204c_resync(uint8_t size, uint8_t *response); + uint8_t sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer, uint8_t execution_delay, uint8_t execution_timeout); public: atsha204Class(uint8_t pin); // Constructor - uint8_t sha204c_wakeup(uint8_t *response); - uint8_t sha204c_sleep(); - uint8_t sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer, uint8_t execution_delay, uint8_t execution_timeout); - uint8_t sha204c_resync(uint8_t size, uint8_t *response); + void sha204c_sleep(); uint8_t sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t param2, uint8_t datalen1, uint8_t *data1, uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer); - uint8_t getSerialNumber(uint8_t *response); + void getSerialNumber(uint8_t *response); }; #endif From 2d2eb74e0a9a4476845e9880fd809b0af2332f64 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 14 Mar 2015 12:37:22 +0100 Subject: [PATCH 083/137] Fixed bug with storing signing table in EEPROM eeprom_updated_block() uses a non-string-standardised order of arguments. --- libraries/MySensors/MySensor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index c058e2e..644b3e1 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -406,7 +406,7 @@ boolean MySensor::process() { CLEAR_SIGN(msg.sender); } // Save updated table - hw_writeConfigBlock((void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, (void*)doSign, sizeof(doSign)); + hw_writeConfigBlock((void*)doSign, (void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, sizeof(doSign)); // Inform sender about our preference if we are a gateway, but only require signing if the sender required signing // We do not currently want a gateway to require signing from all nodes in a network just because it wants one node From 7a2a5dad81e0a3ec30e6167d673d0c9d84f8c5c2 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 14 Mar 2015 13:38:39 +0100 Subject: [PATCH 084/137] Message signing logic now integrated into sendRoute() --- libraries/MySensors/MySensor.cpp | 52 +++++++++++++++++--------------- libraries/MySensors/MySensor.h | 1 - 2 files changed, 27 insertions(+), 26 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 644b3e1..b92f118 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -192,7 +192,33 @@ boolean MySensor::sendRoute(MyMessage &message) { (message.type != I_GET_NONCE && message.type != I_GET_NONCE_RESPONSE && message.type != I_REQUEST_SIGNING && message.type != I_ID_REQUEST && message.type != I_ID_RESPONSE && message.type != I_FIND_PARENT && message.type != I_FIND_PARENT_RESPONSE))) { - if (!sign(message)) { + bool signOk = false; + // Send nonce-request + if (!sendRoute(build(tmpMsg, nc.nodeId, message.destination, message.sensor, C_INTERNAL, I_GET_NONCE, false).set(""))) { + debug(PSTR("nonce tr err\n")); + return false; + } + // We have to wait for the nonce to arrive before we can sign our original message + // Other messages could come in-between. We trust process() takes care of them + unsigned long enter = hw_millis(); + msgSign = message; // Copy the message to sign since message buffer might be touched in process() + while (hw_millis() - enter < MY_VERIFICATION_TIMEOUT_MS) { + if (process()) { + if (mGetCommand(getLastMessage()) == C_INTERNAL && getLastMessage().type == I_GET_NONCE_RESPONSE) { + // Proceed with signing if nonce has been received + if (signer.putNonce(getLastMessage()) && signer.signMsg(msgSign)) { + message = msgSign; // Write the signed message back + signOk = true; + } + break; + } + } + } + if (hw_millis() - enter > MY_VERIFICATION_TIMEOUT_MS) { + debug(PSTR("nonce tmo\n")); + return false; + } + if (!signOk) { debug(PSTR("sign fail\n")); return false; } @@ -524,27 +550,3 @@ int8_t MySensor::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, ui return hw.sleep(interrupt1, mode1, interrupt2, mode2, ms) ; } -bool MySensor::sign(MyMessage &message) { - if (!sendRoute(build(tmpMsg, nc.nodeId, message.destination, message.sensor, C_INTERNAL, I_GET_NONCE, false).set(""))) { - return false; - } else { - // We have to wait for the nonce to arrive before we can sign our original message - // Other messages could come in-between. We trust process() takes care of them - unsigned long enter = hw_millis(); - msgSign = message; // Copy the message to sign since message buffer might be touched in process() - while (hw_millis() - enter < 5000) { - if (process()) { - if (mGetCommand(getLastMessage()) == C_INTERNAL && getLastMessage().type == I_GET_NONCE_RESPONSE) { - // Proceed with signing if nonce has been received - if (signer.putNonce(getLastMessage()) && signer.signMsg(msgSign)) { - message = msgSign; // Write the signed message back - return true; - } - break; - } - } - } - } - return false; -} - diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 9a2ec57..9093183 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -257,7 +257,6 @@ class MySensor void setupNode(); void findParentNode(); uint8_t crc8Message(MyMessage &message); - bool sign(MyMessage &message); }; #endif From 70eac0423d0f8da9b1ba8b6eaa5c440d8cca4a60 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 14 Mar 2015 13:53:11 +0100 Subject: [PATCH 085/137] Added config flag MY_SIGNING_FEATURE in MyConfig.h By disabeling MY_SIGNING_FEATURE all signing logic in the library will be removed. --- libraries/MySensors/MyConfig.h | 3 +++ libraries/MySensors/MySensor.cpp | 24 +++++++++++++++++-- libraries/MySensors/MySensor.h | 14 ++++++++--- .../SecureActuator/SecureActuator.ino | 5 ++++ 4 files changed, 41 insertions(+), 5 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index e68709a..61351af 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -16,6 +16,9 @@ typedef MyHwATMega328 MyHwDriver; /********************************** * Message Signing Settings ***********************************/ +// Disable to completly disable signing functionality in library +#define MY_SIGNING_FEATURE + // Define a suitable timeout for a signature verification session // Consider the turnaround from a nonce being generated to a signed message being received // which might vary, especially in networks with many hops. 5s ought to be enough for anyone. diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index b92f118..aa777d4 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -13,10 +13,12 @@ #define DISTANCE_INVALID (0xFF) +#ifdef MY_SIGNING_FEATURE // Macros for manipulating signing requirement table #define DO_SIGN(node) (node == 0 ? (~doSign[0]&1) : (~doSign[node>>4]&(node%16))) #define SET_SIGN(node) (node == 0 ? (doSign[0]&=~1) : (doSign[node>>4]&=~(node%16))) #define CLEAR_SIGN(node) (node == 0 ? (doSign[0]|=1) : (doSign[node>>4]|=(node%16))) +#endif // Inline function and macros static inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, uint8_t sensor, uint8_t command, uint8_t type, bool enableAck) { @@ -38,10 +40,16 @@ static inline bool isValidDistance( const uint8_t distance ) { } -MySensor::MySensor(MyTransport &_radio, MySigning &_signer, MyHw &_hw) +MySensor::MySensor(MyTransport &_radio, MyHw &_hw +#ifdef MY_SIGNING_FEATURE + , MySigning &_signer +#endif + ) : radio(_radio), +#ifdef MY_SIGNING_FEATURE signer(_signer), +#endif hw(_hw) { } @@ -63,8 +71,10 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b hw_readConfigBlock((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); // Read latest received controller configuration from EEPROM hw_readConfigBlock((void*)&cc, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS, sizeof(ControllerConfig)); +#ifdef MY_SIGNING_FEATURE // Read out the signing requirements from EEPROM hw_readConfigBlock((void*)doSign, (void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, sizeof(doSign)); +#endif if (isGateway) { nc.distance = 0; @@ -128,6 +138,7 @@ void MySensor::setupNode() { // Present node and request config if (!isGateway && nc.nodeId != AUTO) { +#ifdef MY_SIGNING_FEATURE // Notify gateway (and possibly controller) about the signing preferences of this node sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_REQUEST_SIGNING, false).set(signer.requestSignatures())); @@ -135,6 +146,7 @@ void MySensor::setupNode() { if (signer.requestSignatures()) { wait(2000); } +#endif // Send presentation for this radio node (attach present(NODE_SENSOR_ID, repeaterMode? S_ARDUINO_REPEATER_NODE : S_ARDUINO_NODE); @@ -186,6 +198,7 @@ boolean MySensor::sendRoute(MyMessage &message) { mSetVersion(message, PROTOCOL_VERSION); +#ifdef MY_SIGNING_FEATURE // If destination is known to require signed messages and we are the sender, sign this message unless it is an ACK or a handshake message if (DO_SIGN(message.destination) && message.sender == nc.nodeId && !mGetAck(message) && mGetLength(msg) && (mGetCommand(message) != C_INTERNAL || @@ -225,6 +238,7 @@ boolean MySensor::sendRoute(MyMessage &message) { // After this point, only the 'last' member of the message structure is allowed to be altered if the message has been signed, // or signature will become invalid and the message rejected by the receiver } else mSetSigned(message, 0); // Message is not supposed to be signed, make sure it is marked unsigned +#endif if (dest == GATEWAY_ADDRESS || !repeaterMode) { // If destination is the gateway or if we aren't a repeater, let @@ -339,10 +353,13 @@ boolean MySensor::process() { if (!radio.available(&to)) return false; +#ifdef MY_SIGNING_FEATURE (void)signer.checkTimer(); // Manage signing timeout - +#endif + uint8_t len = radio.receive((uint8_t *)&msg); +#ifdef MY_SIGNING_FEATURE // Before processing message, reject unsigned messages if signing is required and check signature (if it is signed and addressed to us) // Note that we do not care at all about any signature found if we do not require signing, nor do we care about ACKs (they are never signed) if (signer.requestSignatures() && msg.destination == nc.nodeId && mGetLength(msg) && !mGetAck(msg) && @@ -360,6 +377,7 @@ boolean MySensor::process() { return false; // This signed message has been tampered with! } } +#endif // Add string termination, good if we later would want to print it. msg.data[mGetLength(msg)] = '\0'; @@ -418,6 +436,7 @@ boolean MySensor::process() { } } return false; +#ifdef MY_SIGNING_FEATURE } else if (type == I_GET_NONCE) { if (signer.getNonce(msg)) { sendRoute(build(msg, nc.nodeId, msg.sender, NODE_SENSOR_ID, C_INTERNAL, I_GET_NONCE_RESPONSE, false)); @@ -446,6 +465,7 @@ boolean MySensor::process() { return false; // Signing request is an internal MySensor protocol message, no need to inform caller about this } else if (type == I_GET_NONCE_RESPONSE) { return true; // Just pass along nonce silently (no need to call callback for these) +#endif } else if (sender == GATEWAY_ADDRESS) { bool isMetric; diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 9093183..0d43da3 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -18,8 +18,10 @@ #include "MyTransport.h" #include "MyTransportNRF24.h" #include "MyParser.h" +#ifdef MY_SIGNING_FEATURE #include "MySigning.h" #include "MySigningNone.h" +#endif #include "MyMessage.h" #include #include @@ -73,7 +75,11 @@ class MySensor * Creates a new instance of Sensor class. * */ - MySensor(MyTransport &radio =*new MyTransportNRF24(), MySigning &signer=*new MySigningNone(), MyHw &hw=*new MyHwDriver()); + MySensor(MyTransport &radio =*new MyTransportNRF24(), MyHw &hw=*new MyHwDriver() +#ifdef MY_SIGNING_FEATURE + , MySigning &signer=*new MySigningNone() +#endif + ); /** * Begin operation of the MySensors library @@ -233,14 +239,16 @@ class MySensor bool repeaterMode; bool autoFindParent; bool isGateway; - uint16_t doSign[16]; // Bitfield indicating which sensors require signed communication MyMessage msg; // Buffer for incoming messages. MyMessage tmpMsg ; // Buffer for temporary messages (acks and nonces among others). +#ifdef MY_SIGNING_FEATURE + uint16_t doSign[16]; // Bitfield indicating which sensors require signed communication MyMessage msgSign; // Buffer for message to sign. + MySigning& signer; +#endif MyTransport& radio; - MySigning& signer; MyHw& hw; boolean sendWrite(uint8_t dest, MyMessage &message); diff --git a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino index 297f6dd..a3ee2bc 100644 --- a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino +++ b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino @@ -20,6 +20,7 @@ MyTransportNRF24 radio; // NRFRF24L01 radio driver MyHwATMega328 hw; // Select AtMega328 hardware profile +#ifdef MY_SIGNING_FEATURE #ifdef MY_SECURE_NODE_WHITELISTING #ifdef USE_SOFTWARE_ATSHA // Change the soft_serial value to an arbitrary value for proper security @@ -43,6 +44,10 @@ MySigningAtsha204 signer; #endif #endif MySensor gw(radio, hw, signer); +#else +#error SecureActuator cannot possibly be secure without signing enabled +MySensor gw(radio, hw); +#endif void setup() { From 6fd26880a2ba06ec9d3b1da67358bacd405fab12 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Mon, 16 Mar 2015 22:45:39 +0100 Subject: [PATCH 086/137] Made "Inclusion started by button" a DEBUG message In other words, the message will only be printed if DEBUG flag is enabled. --- libraries/MySensors/examples/EthernetGateway/GatewayUtil.h | 2 ++ libraries/MySensors/examples/SerialGateway/GatewayUtil.h | 2 ++ 2 files changed, 4 insertions(+) diff --git a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h index d564ea6..6f006df 100644 --- a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h @@ -91,7 +91,9 @@ void checkButtonTriggeredInclusion() { if (buttonTriggeredInclusion) { // Ok, someone pressed the inclusion button on the gateway // start inclusion mode for 1 munute. +#ifdef DEBUG serial(PSTR("0;0;%d;0;%d;Inclusion started by button.\n"), C_INTERNAL, I_LOG_MESSAGE); +#endif buttonTriggeredInclusion = false; setInclusionMode(true); } diff --git a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h index d564ea6..6f006df 100644 --- a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h @@ -91,7 +91,9 @@ void checkButtonTriggeredInclusion() { if (buttonTriggeredInclusion) { // Ok, someone pressed the inclusion button on the gateway // start inclusion mode for 1 munute. +#ifdef DEBUG serial(PSTR("0;0;%d;0;%d;Inclusion started by button.\n"), C_INTERNAL, I_LOG_MESSAGE); +#endif buttonTriggeredInclusion = false; setInclusionMode(true); } From 6fb726675272738a4fbb2f369ea7bbe73b82023a Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Mon, 16 Mar 2015 22:53:27 +0100 Subject: [PATCH 087/137] Removed 'new' from PinChangeInt library As a consequence, only one pin is currently suppored. AddPin will not really add a new pin, just replace the configuration of the existing pin. The motivation for this limitation is that 'new' costs a lot of program memory. --- libraries/PinChangeInt/PinChangeInt.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/libraries/PinChangeInt/PinChangeInt.h b/libraries/PinChangeInt/PinChangeInt.h index 19be5a6..807b20d 100644 --- a/libraries/PinChangeInt/PinChangeInt.h +++ b/libraries/PinChangeInt/PinChangeInt.h @@ -234,6 +234,7 @@ protected: volatile uint8_t portFallingPins; volatile uint8_t lastPinView; PCintPin* firstPin; + PCintPin thePin; }; #ifndef LIBCALL_PINCHANGEINT // LIBCALL_PINCHANGEINT *********************************************** @@ -388,8 +389,9 @@ int8_t PCintPort::addPin(uint8_t arduinoPin, PCIntvoidFuncPtr userFunc, uint8_t } while (true); } - // Create pin p: fill in the data. - PCintPin* p=new PCintPin; + // Create pin p: fill in the data. NOTE: MySensors only support one pin due to size constraints + // TODO: Figure out a better way to solve this without relying on new/malloc + PCintPin* p = &thePin; //PCintPin* p=new PCintPin; if (p == NULL) return(-1); p->arduinoPin=arduinoPin; p->mode = mode; From f8281302eb98daea26dc728a08c4a32eacb8d3bf Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Wed, 18 Mar 2015 22:31:14 +0100 Subject: [PATCH 088/137] Fixed software signing whitelisting example in SecureActuator The software serial is now provided to the backend as it should be. --- libraries/MySensors/examples/SecureActuator/SecureActuator.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino index a3ee2bc..73bf57d 100644 --- a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino +++ b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino @@ -32,7 +32,7 @@ whitelist_entry_t node_whitelist[] = { .serial = {0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01} } }; #ifdef USE_SOFTWARE_ATSHA -MySigningAtsha204Soft signer; // Message signing driver +MySigningAtsha204Soft signer(true, 1, node_whitelist, soft_serial); // Message signing driver #else MySigningAtsha204 signer(true, 1, node_whitelist); #endif From aa3fd74139cc82b1f0a2f77a90a75df75a2e9d18 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Fri, 20 Mar 2015 09:52:36 +0100 Subject: [PATCH 089/137] Update to cope with disabled signing. --- libraries/MySensors/examples/RelayActuator/RelayActuator.ino | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino index 2bb49ab..9a7e7c7 100644 --- a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino +++ b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino @@ -15,11 +15,11 @@ // NRFRF24L01 radio driver (set low transmit power by default) MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); // Message signing driver (none default) -MySigningNone signer; +// MySigningNone signer; // Select AtMega328 hardware profile MyHwATMega328 hw; // Construct MySensors library -MySensor gw(radio, signer, hw); +MySensor gw(radio, hw); void setup() { From b72ac4b2776f7234207eabc626311688c0de7c20 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Fri, 20 Mar 2015 19:45:26 +0100 Subject: [PATCH 090/137] Fix crash when debug enabled. --- libraries/MySensors/MyConfig.h | 6 ++---- libraries/MySensors/MyHw.h | 1 + libraries/MySensors/MyHwATMega328.h | 2 +- libraries/MySensors/MySensor.h | 7 +++++++ 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 61351af..a4f8a53 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -9,15 +9,13 @@ // Serial output baud rate #define BAUD_RATE 115200 -// Set the hardware driver to use (initialized by MySensor-class) -#include "MyHwATMega328.h" -typedef MyHwATMega328 MyHwDriver; + /********************************** * Message Signing Settings ***********************************/ // Disable to completly disable signing functionality in library -#define MY_SIGNING_FEATURE +//#define MY_SIGNING_FEATURE // Define a suitable timeout for a signature verification session // Consider the turnaround from a nonce being generated to a signed message being received diff --git a/libraries/MySensors/MyHw.h b/libraries/MySensors/MyHw.h index b73ec23..14857c6 100644 --- a/libraries/MySensors/MyHw.h +++ b/libraries/MySensors/MyHw.h @@ -3,6 +3,7 @@ #include #include +#include "MyConfig.h" /** * The Hw contains all hardware specific details of the platform diff --git a/libraries/MySensors/MyHwATMega328.h b/libraries/MySensors/MyHwATMega328.h index 5a63faf..684ef59 100644 --- a/libraries/MySensors/MyHwATMega328.h +++ b/libraries/MySensors/MyHwATMega328.h @@ -2,7 +2,7 @@ #define MyHwATMega328_h #include "MyHw.h" -//#include "MyConfig.h" +#include "MyConfig.h" #include "MyMessage.h" #include #include diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 0d43da3..df297cf 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -27,6 +27,13 @@ #include +// Set the hardware driver to use (initialized by MySensor-class) +#if defined __AVR_ATmega328P__ +#include "MyHwATMega328.h" +typedef MyHwATMega328 MyHwDriver; +#endif + + #ifdef DEBUG #define debug(x,...) hw.debugPrint(isGateway, x, ##__VA_ARGS__) #else From dbe06255fcc95a86ec09488d339c40b98c0a0071 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Fri, 20 Mar 2015 19:47:32 +0100 Subject: [PATCH 091/137] New data type V_ID used for sensors with id such as DS1820b --- libraries/MySensors/MyMessage.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index 2616c32..c2698bc 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -39,7 +39,10 @@ typedef enum { V_IMPEDANCE, V_ARMED, V_TRIPPED, V_WATT, V_KWH, V_SCENE_ON, V_SCENE_OFF, V_HEATER, V_HEATER_SW, V_LIGHT_LEVEL, V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, V_UP, V_DOWN, V_STOP, V_IR_SEND, V_IR_RECEIVE, V_FLOW, V_VOLUME, V_LOCK_STATUS, - V_DUST_LEVEL, V_VOLTAGE, V_CURRENT, V_RGB, V_RGBW + V_DUST_LEVEL, V_VOLTAGE, V_CURRENT, + V_RGB, // Used for sending/receiving color information. Sent as ascii hex. RRGGBB (RR=red, GG=green, BB=blue component) + V_RGBW, // Used for sending/receiving color information. Sent as ascii hex. RRGGBBWW (WW=while component) + V_ID // Can be used for reporting ids for sensors such as DS1820b. } mysensor_data; // Type of internal messages (for internal messages) From adca8b5a4ce1d2cee8d854e919754bf1b42db56f Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 24 Mar 2015 10:58:28 +0100 Subject: [PATCH 092/137] Temporary OTA commit --- libraries/MySensors/MyConfig.h | 15 +- libraries/MySensors/MyHwATMega328.h | 2 + libraries/MySensors/MySensor.cpp | 30 +++ libraries/MySensors/MySensor.h | 41 +++ .../examples/RelayActuator/RelayActuator.ino | 4 +- libraries/MySensors/utility/SPIFlash.cpp | 246 ++++++++++++++++++ libraries/MySensors/utility/SPIFlash.h | 100 +++++++ 7 files changed, 436 insertions(+), 2 deletions(-) create mode 100644 libraries/MySensors/utility/SPIFlash.cpp create mode 100644 libraries/MySensors/utility/SPIFlash.h diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index a4f8a53..5f6423f 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -6,10 +6,23 @@ // to see what is actually is happening when developing #define DEBUG -// Serial output baud rate +// Serial output baud rate (for debug prints and serial gateway) #define BAUD_RATE 115200 +/********************************** +* Over the air firmware updates +***********************************/ + +// The following define enables the safe over-the-air firmware update feature +// which requires external flash and the DualOptiBoot bootloader. +// Note: You can still have OTA FW updates without external flash but it +// requires the MYSBootloader and disabled MY_OTA_FIRMWARE_FEATURE +#define MY_OTA_FIRMWARE_FEATURE + +// Slave select pin for external flash +#define MY_OTA_FLASH_SS 8 + /********************************** * Message Signing Settings diff --git a/libraries/MySensors/MyHwATMega328.h b/libraries/MySensors/MyHwATMega328.h index 684ef59..b45a5b9 100644 --- a/libraries/MySensors/MyHwATMega328.h +++ b/libraries/MySensors/MyHwATMega328.h @@ -10,6 +10,8 @@ #include #include #include +#include + #ifdef __cplusplus diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index aa777d4..c8e118f 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -55,6 +55,30 @@ MySensor::MySensor(MyTransport &_radio, MyHw &_hw } +#ifdef MY_OTA_FRIMWARE_FEATURE +// do a crc16 on the whole received firmware +static uint8_t MySensor::isValidFirmware() { + void* ptr = 0; + uint16_t crc = ~0; + int j; + + for (uint16_t i = 0; i < fc.blocks * FIRMWARE_BLOCK_SIZE; ++i) { + uint8_t a = pgm_read_byte((uint16_t) ptr + i); + crc ^= a; + for (j = 0; j < 8; ++j) + { + if (crc & 1) + crc = (crc >> 1) ^ 0xA001; + else + crc = (crc >> 1); + } + } + return crc == fc.crc; +} + +#endif + + void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId) { hw_init(); repeaterMode = _repeaterMode; @@ -71,6 +95,12 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b hw_readConfigBlock((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); // Read latest received controller configuration from EEPROM hw_readConfigBlock((void*)&cc, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS, sizeof(ControllerConfig)); +#ifdef MY_OTA_FRIMWARE_FEATURE + // Read firmware config from EEPROM, i.e. type, version, CRC, blocks + hw_readConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig)); +#endif + + #ifdef MY_SIGNING_FEATURE // Read out the signing requirements from EEPROM hw_readConfigBlock((void*)doSign, (void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, sizeof(doSign)); diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index df297cf..bb68d01 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -61,6 +61,7 @@ typedef MyHwATMega328 MyHwDriver; // Search for a new parent node after this many transmission failures #define SEARCH_FAILURES 5 + struct NodeConfig { uint8_t nodeId; // Current node id @@ -72,6 +73,42 @@ struct ControllerConfig { uint8_t isMetric; }; + +// Size of each firmware block +#define FIRMWARE_BLOCK_SIZE 16 +// Number of times a firmware block should be requested before giving up +#define FIRMWARE_MAX_REQUESTS 5 + +// FW config structure, stored in eeprom +typedef struct { + uint16_t type; + uint16_t version; + uint16_t blocks; + uint16_t crc; +} __attribute__((packed)) NodeFirmwareConfig; + +typedef struct { + uint16_t type; + uint16_t version; + uint16_t blocks; + uint16_t crc; + uint16_t BLVersion; +} __attribute__((packed)) RequestFirmwareConfig; + +typedef struct { + uint16_t type; + uint16_t version; + uint16_t block; +} __attribute__((packed)) RequestFWBlock; + +typedef struct { + uint16_t type; + uint16_t version; + uint16_t block; + uint8_t data[FIRMWARE_BLOCK_SIZE]; +} __attribute__((packed)) ReplyFWBlock; + + #ifdef __cplusplus class MySensor { @@ -243,6 +280,10 @@ class MySensor protected: NodeConfig nc; // Essential settings for node to work ControllerConfig cc; // Configuration coming from controller +#ifdef MY_OTA_FIRMWARE_FEATURE + NodeFirmwareConfig fc; +#endif + bool repeaterMode; bool autoFindParent; bool isGateway; diff --git a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino index 9a7e7c7..615049d 100644 --- a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino +++ b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino @@ -3,6 +3,7 @@ #include #include +//#include #include #include #include @@ -14,8 +15,9 @@ // NRFRF24L01 radio driver (set low transmit power by default) MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +//MyTransportRF69 radio; // Message signing driver (none default) -// MySigningNone signer; +//MySigningNone signer; // Select AtMega328 hardware profile MyHwATMega328 hw; // Construct MySensors library diff --git a/libraries/MySensors/utility/SPIFlash.cpp b/libraries/MySensors/utility/SPIFlash.cpp new file mode 100644 index 0000000..03d6a1a --- /dev/null +++ b/libraries/MySensors/utility/SPIFlash.cpp @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2013 by Felix Rusu + * SPI Flash memory library for arduino/moteino. + * This works with 256byte/page SPI flash memory + * For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) + * Minimal modifications should allow chips that have different page size but modifications + * DEPENDS ON: Arduino SPI library + * + * This file is free software; you can redistribute it and/or modify + * it under the terms of either the GNU General Public License version 2 + * or the GNU Lesser General Public License version 2.1, both as + * published by the Free Software Foundation. + */ + +#include + +byte SPIFlash::UNIQUEID[8]; + +/// IMPORTANT: NAND FLASH memory requires erase before write, because +/// it can only transition from 1s to 0s and only the erase command can reset all 0s to 1s +/// See http://en.wikipedia.org/wiki/Flash_memory +/// The smallest range that can be erased is a sector (4K, 32K, 64K); there is also a chip erase command + +/// Constructor. JedecID is optional but recommended, since this will ensure that the device is present and has a valid response +/// get this from the datasheet of your flash chip +/// Example for Atmel-Adesto 4Mbit AT25DF041A: 0x1F44 (page 27: http://www.adestotech.com/sites/default/files/datasheets/doc3668.pdf) +/// Example for Winbond 4Mbit W25X40CL: 0xEF30 (page 14: http://www.winbond.com/NR/rdonlyres/6E25084C-0BFE-4B25-903D-AE10221A0929/0/W25X40CL.pdf) +SPIFlash::SPIFlash(uint8_t slaveSelectPin, uint16_t jedecID) { + _slaveSelectPin = slaveSelectPin; + _jedecID = jedecID; +} + +/// Select the flash chip +void SPIFlash::select() { + noInterrupts(); + //save current SPI settings + _SPCR = SPCR; + _SPSR = SPSR; + //set FLASH chip SPI settings + SPI.setDataMode(SPI_MODE0); + SPI.setBitOrder(MSBFIRST); + SPI.setClockDivider(SPI_CLOCK_DIV4); //decided to slow down from DIV2 after SPI stalling in some instances, especially visible on mega1284p when RFM69 and FLASH chip both present + SPI.begin(); + digitalWrite(_slaveSelectPin, LOW); +} + +/// UNselect the flash chip +void SPIFlash::unselect() { + digitalWrite(_slaveSelectPin, HIGH); + //restore SPI settings to what they were before talking to the FLASH chip + SPCR = _SPCR; + SPSR = _SPSR; + interrupts(); +} + +/// setup SPI, read device ID etc... +boolean SPIFlash::initialize() +{ + _SPCR = SPCR; + _SPSR = SPSR; + pinMode(_slaveSelectPin, OUTPUT); + unselect(); + wakeup(); + + if (_jedecID == 0 || readDeviceId() == _jedecID) { + command(SPIFLASH_STATUSWRITE, true); // Write Status Register + SPI.transfer(0); // Global Unprotect + unselect(); + return true; + } + return false; +} + +/// Get the manufacturer and device ID bytes (as a short word) +word SPIFlash::readDeviceId() +{ +#if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo + command(SPIFLASH_IDREAD); // Read JEDEC ID +#else + select(); + SPI.transfer(SPIFLASH_IDREAD); +#endif + word jedecid = SPI.transfer(0) << 8; + jedecid |= SPI.transfer(0); + unselect(); + return jedecid; +} + +/// Get the 64 bit unique identifier, stores it in UNIQUEID[8]. Only needs to be called once, ie after initialize +/// Returns the byte pointer to the UNIQUEID byte array +/// Read UNIQUEID like this: +/// flash.readUniqueId(); for (byte i=0;i<8;i++) { Serial.print(flash.UNIQUEID[i], HEX); Serial.print(' '); } +/// or like this: +/// flash.readUniqueId(); byte* MAC = flash.readUniqueId(); for (byte i=0;i<8;i++) { Serial.print(MAC[i], HEX); Serial.print(' '); } +byte* SPIFlash::readUniqueId() +{ + command(SPIFLASH_MACREAD); + SPI.transfer(0); + SPI.transfer(0); + SPI.transfer(0); + SPI.transfer(0); + for (byte i=0;i<8;i++) + UNIQUEID[i] = SPI.transfer(0); + unselect(); + return UNIQUEID; +} + +/// read 1 byte from flash memory +byte SPIFlash::readByte(long addr) { + command(SPIFLASH_ARRAYREADLOWFREQ); + SPI.transfer(addr >> 16); + SPI.transfer(addr >> 8); + SPI.transfer(addr); + byte result = SPI.transfer(0); + unselect(); + return result; +} + +/// read unlimited # of bytes +void SPIFlash::readBytes(long addr, void* buf, word len) { + command(SPIFLASH_ARRAYREAD); + SPI.transfer(addr >> 16); + SPI.transfer(addr >> 8); + SPI.transfer(addr); + SPI.transfer(0); //"dont care" + for (word i = 0; i < len; ++i) + ((byte*) buf)[i] = SPI.transfer(0); + unselect(); +} + +/// Send a command to the flash chip, pass TRUE for isWrite when its a write command +void SPIFlash::command(byte cmd, boolean isWrite){ +#if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo + DDRB |= B00000001; // Make sure the SS pin (PB0 - used by RFM12B on MoteinoLeo R1) is set as output HIGH! + PORTB |= B00000001; +#endif + if (isWrite) + { + command(SPIFLASH_WRITEENABLE); // Write Enable + unselect(); + } + //wait for any write/erase to complete + // a time limit cannot really be added here without it being a very large safe limit + // that is because some chips can take several seconds to carry out a chip erase or other similar multi block or entire-chip operations + // a recommended alternative to such situations where chip can be or not be present is to add a 10k or similar weak pulldown on the + // open drain MISO input which can read noise/static and hence return a non 0 status byte, causing the while() to hang when a flash chip is not present + while(busy()); + select(); + SPI.transfer(cmd); +} + +/// check if the chip is busy erasing/writing +boolean SPIFlash::busy() +{ + /* + select(); + SPI.transfer(SPIFLASH_STATUSREAD); + byte status = SPI.transfer(0); + unselect(); + return status & 1; + */ + return readStatus() & 1; +} + +/// return the STATUS register +byte SPIFlash::readStatus() +{ + select(); + SPI.transfer(SPIFLASH_STATUSREAD); + byte status = SPI.transfer(0); + unselect(); + return status; +} + + +/// Write 1 byte to flash memory +/// WARNING: you can only write to previously erased memory locations (see datasheet) +/// use the block erase commands to first clear memory (write 0xFFs) +void SPIFlash::writeByte(long addr, uint8_t byt) { + command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program + SPI.transfer(addr >> 16); + SPI.transfer(addr >> 8); + SPI.transfer(addr); + SPI.transfer(byt); + unselect(); +} + +/// write 1-256 bytes to flash memory +/// WARNING: you can only write to previously erased memory locations (see datasheet) +/// use the block erase commands to first clear memory (write 0xFFs) +/// WARNING: if you write beyond a page boundary (or more than 256bytes), +/// the bytes will wrap around and start overwriting at the beginning of that same page +/// see datasheet for more details +void SPIFlash::writeBytes(long addr, const void* buf, uint16_t len) { + command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program + SPI.transfer(addr >> 16); + SPI.transfer(addr >> 8); + SPI.transfer(addr); + for (uint16_t i = 0; i < len; i++) + SPI.transfer(((byte*) buf)[i]); + unselect(); +} + +/// erase entire flash memory array +/// may take several seconds depending on size, but is non blocking +/// so you may wait for this to complete using busy() or continue doing +/// other things and later check if the chip is done with busy() +/// note that any command will first wait for chip to become available using busy() +/// so no need to do that twice +void SPIFlash::chipErase() { + command(SPIFLASH_CHIPERASE, true); + unselect(); +} + +/// erase a 4Kbyte block +void SPIFlash::blockErase4K(long addr) { + command(SPIFLASH_BLOCKERASE_4K, true); // Block Erase + SPI.transfer(addr >> 16); + SPI.transfer(addr >> 8); + SPI.transfer(addr); + unselect(); +} + +/// erase a 32Kbyte block +void SPIFlash::blockErase32K(long addr) { + command(SPIFLASH_BLOCKERASE_32K, true); // Block Erase + SPI.transfer(addr >> 16); + SPI.transfer(addr >> 8); + SPI.transfer(addr); + unselect(); +} + +void SPIFlash::sleep() { + command(SPIFLASH_SLEEP); + unselect(); +} + +void SPIFlash::wakeup() { + command(SPIFLASH_WAKE); + unselect(); +} + +/// cleanup +void SPIFlash::end() { + SPI.end(); +} \ No newline at end of file diff --git a/libraries/MySensors/utility/SPIFlash.h b/libraries/MySensors/utility/SPIFlash.h new file mode 100644 index 0000000..f0c071a --- /dev/null +++ b/libraries/MySensors/utility/SPIFlash.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2013 by Felix Rusu + * SPI Flash memory library for arduino/moteino. + * This works with 256byte/page SPI flash memory + * For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) + * Minimal modifications should allow chips that have different page size but modifications + * DEPENDS ON: Arduino SPI library + * + * This file is free software; you can redistribute it and/or modify + * it under the terms of either the GNU General Public License version 2 + * or the GNU Lesser General Public License version 2.1, both as + * published by the Free Software Foundation. + */ + +#ifndef _SPIFLASH_H_ +#define _SPIFLASH_H_ + +#if ARDUINO >= 100 +#include +#else +#include +#include "pins_arduino.h" +#endif + +#include + +/// IMPORTANT: NAND FLASH memory requires erase before write, because +/// it can only transition from 1s to 0s and only the erase command can reset all 0s to 1s +/// See http://en.wikipedia.org/wiki/Flash_memory +/// The smallest range that can be erased is a sector (4K, 32K, 64K); there is also a chip erase command + +/// Standard SPI flash commands +/// Assuming the WP pin is pulled up (to disable hardware write protection) +/// To use any write commands the WEL bit in the status register must be set to 1. +/// This is accomplished by sending a 0x06 command before any such write/erase command. +/// The WEL bit in the status register resets to the logical “0” state after a +/// device power-up or reset. In addition, the WEL bit will be reset to the logical “0” state automatically under the following conditions: +/// • Write Disable operation completes successfully +/// • Write Status Register operation completes successfully or aborts +/// • Protect Sector operation completes successfully or aborts +/// • Unprotect Sector operation completes successfully or aborts +/// • Byte/Page Program operation completes successfully or aborts +/// • Sequential Program Mode reaches highest unprotected memory location +/// • Sequential Program Mode reaches the end of the memory array +/// • Sequential Program Mode aborts +/// • Block Erase operation completes successfully or aborts +/// • Chip Erase operation completes successfully or aborts +/// • Hold condition aborts +#define SPIFLASH_WRITEENABLE 0x06 // write enable +#define SPIFLASH_WRITEDISABLE 0x04 // write disable + +#define SPIFLASH_BLOCKERASE_4K 0x20 // erase one 4K block of flash memory +#define SPIFLASH_BLOCKERASE_32K 0x52 // erase one 32K block of flash memory +#define SPIFLASH_BLOCKERASE_64K 0xD8 // erase one 64K block of flash memory +#define SPIFLASH_CHIPERASE 0x60 // chip erase (may take several seconds depending on size) + // but no actual need to wait for completion (instead need to check the status register BUSY bit) +#define SPIFLASH_STATUSREAD 0x05 // read status register +#define SPIFLASH_STATUSWRITE 0x01 // write status register +#define SPIFLASH_ARRAYREAD 0x0B // read array (fast, need to add 1 dummy byte after 3 address bytes) +#define SPIFLASH_ARRAYREADLOWFREQ 0x03 // read array (low frequency) + +#define SPIFLASH_SLEEP 0xB9 // deep power down +#define SPIFLASH_WAKE 0xAB // deep power wake up +#define SPIFLASH_BYTEPAGEPROGRAM 0x02 // write (1 to 256bytes) +#define SPIFLASH_IDREAD 0x9F // read JEDEC manufacturer and device ID (2 bytes, specific bytes for each manufacturer and device) + // Example for Atmel-Adesto 4Mbit AT25DF041A: 0x1F44 (page 27: http://www.adestotech.com/sites/default/files/datasheets/doc3668.pdf) + // Example for Winbond 4Mbit W25X40CL: 0xEF30 (page 14: http://www.winbond.com/NR/rdonlyres/6E25084C-0BFE-4B25-903D-AE10221A0929/0/W25X40CL.pdf) +#define SPIFLASH_MACREAD 0x4B // read unique ID number (MAC) + +class SPIFlash { +public: + static byte UNIQUEID[8]; + SPIFlash(byte slaveSelectPin, uint16_t jedecID=0); + boolean initialize(); + void command(byte cmd, boolean isWrite=false); + byte readStatus(); + byte readByte(long addr); + void readBytes(long addr, void* buf, word len); + void writeByte(long addr, byte byt); + void writeBytes(long addr, const void* buf, uint16_t len); + boolean busy(); + void chipErase(); + void blockErase4K(long address); + void blockErase32K(long address); + word readDeviceId(); + byte* readUniqueId(); + + void sleep(); + void wakeup(); + void end(); +protected: + void select(); + void unselect(); + byte _slaveSelectPin; + uint16_t _jedecID; + byte _SPCR; + byte _SPSR; +}; + +#endif \ No newline at end of file From 663c0386ea72b9e49fb8b55736c4e02b2a1d6dd4 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 24 Mar 2015 11:05:48 +0100 Subject: [PATCH 093/137] Light Lux level data type added --- libraries/MySensors/MyMessage.h | 3 ++- libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index c2698bc..93edc74 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -42,7 +42,8 @@ typedef enum { V_DUST_LEVEL, V_VOLTAGE, V_CURRENT, V_RGB, // Used for sending/receiving color information. Sent as ascii hex. RRGGBB (RR=red, GG=green, BB=blue component) V_RGBW, // Used for sending/receiving color information. Sent as ascii hex. RRGGBBWW (WW=while component) - V_ID // Can be used for reporting ids for sensors such as DS1820b. + V_ID, // Can be used for reporting ids for sensors such as DS1820b. + V_LIGHT_LEVEL_LUX // Light level in lux } mysensor_data; // Type of internal messages (for internal messages) diff --git a/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino b/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino index 441c65e..2896056 100644 --- a/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino +++ b/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino @@ -27,7 +27,7 @@ unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) BH1750 lightSensor; MySensor gw; -MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL); +MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL_LUX); uint16_t lastlux; void setup() From c1a9a53ab916f9d9c431af4d4b3c89726871f1d5 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 26 Mar 2015 14:30:07 +0100 Subject: [PATCH 094/137] WIP --- libraries/MySensors/MyConfig.h | 9 ++++++++- libraries/MySensors/MySensor.cpp | 29 ++++++++++++++++++++++++++++- libraries/MySensors/MySensor.h | 6 ++++++ 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 5f6423f..4e5b579 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -19,9 +19,16 @@ // Note: You can still have OTA FW updates without external flash but it // requires the MYSBootloader and disabled MY_OTA_FIRMWARE_FEATURE #define MY_OTA_FIRMWARE_FEATURE - // Slave select pin for external flash #define MY_OTA_FLASH_SS 8 +// Number of times to request a fw block before giving up +#define MY_OTA_RETRY 5 +// Number of millisecons before re-request a fw block +#define MY_OTA_RETRY_DELAY 500 +// Bootloader version +#define MY_OTA_BOOTLOADER_MAJOR_VERSION 2 +#define MY_OTA_BOOTLOADER_MINOR_VERSION 0 +#define MY_OTA_BOOTLOADER_VERSION (MY_OTA_BOOTLOADER_MINOR_VERSION * 256 + MY_OTA_BOOTLOADER_MAJOR_VERSION) /********************************** diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index c8e118f..4be0330 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -57,7 +57,7 @@ MySensor::MySensor(MyTransport &_radio, MyHw &_hw #ifdef MY_OTA_FRIMWARE_FEATURE // do a crc16 on the whole received firmware -static uint8_t MySensor::isValidFirmware() { +bool MySensor::isValidFirmware() { void* ptr = 0; uint16_t crc = ~0; int j; @@ -188,6 +188,33 @@ void MySensor::setupNode() { // Wait configuration reply. wait(2000); + +#ifdef MY_OTA_FRIMWARE_FEATURE + RequestFirmwareConfig *reqFWConfig = (RequestFirmwareConfig *)msg.data; + mSetLength(msg, sizeof(RequestFirmwareConfig)); + mSetCommand(msg, C_STREAM); + mSetPayloadType(msg,P_CUSTOM); + // copy node settings to reqFWConfig + memcpy(reqFWConfig,&fc,sizeof(NodeFirmwareConfig)); + // add bootloader information + reqFWConfig->BLVersion = MYSBOOTLOADER_VERSION; + + // send node config and request FW config from controller + if (!sendAndWait(ST_FIRMWARE_CONFIG_REQUEST, ST_FIRMWARE_CONFIG_RESPONSE)) { + startup(); + } + + NodeFirmwareConfig *firmwareConfigResponse = (NodeFirmwareConfig *)inMsg.data; + + // compare with current node configuration, if equal startup + if (!memcmp(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig))) { + startup(); + } + + +#endif + + } } diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index bb68d01..40e5cd4 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -309,6 +309,12 @@ class MySensor void (*timeCallback)(unsigned long); // Callback for requested time messages void (*msgCallback)(const MyMessage &); // Callback for incoming messages from other nodes and gateway. +#ifdef MY_OTA_FRIMWARE_FEATURE +// do a crc16 on the whole received firmware + bool isValidFirmware(); +#endif + + void requestNodeId(); void setupNode(); void findParentNode(); From 6da96e7d40e785ded232450adfe41cfc120da6e1 Mon Sep 17 00:00:00 2001 From: tekka Date: Thu, 26 Mar 2015 14:33:44 +0100 Subject: [PATCH 095/137] adding back time handler was missing in dev branch --- libraries/MySensors/MySensor.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index aa777d4..ebb69ef 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -506,6 +506,11 @@ boolean MySensor::process() { findParentNode(); sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_CHILDREN,false).set("")); } + } else if (type == I_TIME) { + if (timeCallback != NULL) { + // Deliver time to callback + timeCallback(msg.getULong()); + } } return false; } From 3a59929b8ed8e1fca9876031264db5d6626876ff Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 30 Mar 2015 10:28:57 +0200 Subject: [PATCH 096/137] Initial untested OTA feature --- libraries/MySensors/MyConfig.h | 10 +- libraries/MySensors/MyHwATMega328.h | 1 - libraries/MySensors/MySensor.cpp | 137 +++++++++++++++++++++++----- libraries/MySensors/MySensor.h | 21 ++++- 4 files changed, 136 insertions(+), 33 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 4e5b579..4b7b4f1 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -21,14 +21,8 @@ #define MY_OTA_FIRMWARE_FEATURE // Slave select pin for external flash #define MY_OTA_FLASH_SS 8 -// Number of times to request a fw block before giving up -#define MY_OTA_RETRY 5 -// Number of millisecons before re-request a fw block -#define MY_OTA_RETRY_DELAY 500 -// Bootloader version -#define MY_OTA_BOOTLOADER_MAJOR_VERSION 2 -#define MY_OTA_BOOTLOADER_MINOR_VERSION 0 -#define MY_OTA_BOOTLOADER_VERSION (MY_OTA_BOOTLOADER_MINOR_VERSION * 256 + MY_OTA_BOOTLOADER_MAJOR_VERSION) +// Flash jdecid +#define MY_OTA_FLASH_JDECID 0x1F65 /********************************** diff --git a/libraries/MySensors/MyHwATMega328.h b/libraries/MySensors/MyHwATMega328.h index b45a5b9..8610f1b 100644 --- a/libraries/MySensors/MyHwATMega328.h +++ b/libraries/MySensors/MyHwATMega328.h @@ -10,7 +10,6 @@ #include #include #include -#include diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 4be0330..c05df58 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -49,13 +49,16 @@ MySensor::MySensor(MyTransport &_radio, MyHw &_hw radio(_radio), #ifdef MY_SIGNING_FEATURE signer(_signer), +#endif +#ifdef MY_OTA_FIRMWARE_FEATURE + flash(MY_OTA_FLASH_SS, MY_OTA_FLASH_JDECID), #endif hw(_hw) { } -#ifdef MY_OTA_FRIMWARE_FEATURE +#ifdef MY_OTA_FIRMWARE_FEATURE // do a crc16 on the whole received firmware bool MySensor::isValidFirmware() { void* ptr = 0; @@ -63,7 +66,7 @@ bool MySensor::isValidFirmware() { int j; for (uint16_t i = 0; i < fc.blocks * FIRMWARE_BLOCK_SIZE; ++i) { - uint8_t a = pgm_read_byte((uint16_t) ptr + i); + uint8_t a = flash.readByte((uint16_t) ptr + i + FIRMWARE_START_OFFSET); crc ^= a; for (j = 0; j < 8; ++j) { @@ -95,7 +98,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b hw_readConfigBlock((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); // Read latest received controller configuration from EEPROM hw_readConfigBlock((void*)&cc, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS, sizeof(ControllerConfig)); -#ifdef MY_OTA_FRIMWARE_FEATURE +#ifdef MY_OTA_FIRMWARE_FEATURE // Read firmware config from EEPROM, i.e. type, version, CRC, blocks hw_readConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig)); #endif @@ -189,7 +192,7 @@ void MySensor::setupNode() { // Wait configuration reply. wait(2000); -#ifdef MY_OTA_FRIMWARE_FEATURE +#ifdef MY_OTA_FIRMWARE_FEATURE RequestFirmwareConfig *reqFWConfig = (RequestFirmwareConfig *)msg.data; mSetLength(msg, sizeof(RequestFirmwareConfig)); mSetCommand(msg, C_STREAM); @@ -197,21 +200,9 @@ void MySensor::setupNode() { // copy node settings to reqFWConfig memcpy(reqFWConfig,&fc,sizeof(NodeFirmwareConfig)); // add bootloader information - reqFWConfig->BLVersion = MYSBOOTLOADER_VERSION; - - // send node config and request FW config from controller - if (!sendAndWait(ST_FIRMWARE_CONFIG_REQUEST, ST_FIRMWARE_CONFIG_RESPONSE)) { - startup(); - } - - NodeFirmwareConfig *firmwareConfigResponse = (NodeFirmwareConfig *)inMsg.data; - - // compare with current node configuration, if equal startup - if (!memcmp(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig))) { - startup(); - } - - + reqFWConfig->BLVersion = MY_OTA_BOOTLOADER_VERSION; + fwUpdateOngoing = false; + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_STREAM, ST_FIRMWARE_CONFIG_REQUEST, false)); #endif @@ -408,7 +399,29 @@ boolean MySensor::process() { hw_watchdogReset(); uint8_t to = 0; if (!radio.available(&to)) + { +#ifdef MY_OTA_FIRMWARE_FEATURE + unsigned long enter = hw_millis(); + if (fwUpdateOngoing && (enter - fwLastRequestTime > MY_OTA_RETRY_DELAY)) { + if (fwRetry == 0) { + debug(PSTR("fw upd fail\n")); + // Give up. We have requested MY_OTA_RETRY times without any packet in return. + fwUpdateOngoing = false; + return false; + } + fwRetry--; + fwLastRequestTime = enter; + // Time to (re-)request firmware block from controller + RequestFWBlock *firmwareRequest = (RequestFWBlock *)msg.data; + mSetLength(msg, sizeof(RequestFWBlock)); + firmwareRequest->type = fc.type; + firmwareRequest->version = fc.version; + firmwareRequest->block = (fwBlock - 1); + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_STREAM, ST_FIRMWARE_REQUEST, false)); + } +#endif return false; + } #ifdef MY_SIGNING_FEATURE (void)signer.checkTimer(); // Manage signing timeout @@ -567,6 +580,55 @@ boolean MySensor::process() { return false; } } +#ifdef MY_OTA_FIRMWARE_FEATURE + else if (command == C_STREAM) { + if (type == ST_FIRMWARE_CONFIG_RESPONSE) { + NodeFirmwareConfig *firmwareConfigResponse = (NodeFirmwareConfig *)msg.data; + // compare with current node configuration, if they differ, start fw fetch process + if (memcmp(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig))) { + debug(PSTR("fw update\n")); + fwUpdateOngoing = true; + fwBlock = fc.blocks; + // copy new FW config + memcpy(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig)); + // Init flash + if (!flash.initialize()) { + debug(PSTR("flash init fail\n")); + } + + } + } else if (type == ST_FIRMWARE_RESPONSE) { + // Save block to eeprom + debug(PSTR("fw block %d\n"), fwBlock); + + ReplyFWBlock *firmwareResponse = (ReplyFWBlock *)msg.data; + // write to flash + flash.writeBytes(((fwBlock-1)*FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE); + fwBlock--; + if (fwBlock == 0) { + // We're finished! Do a checksum and reboot. + if (isValidFirmware()) { + debug(PSTR("fw checksum ok\n")); + // All seems ok, write size and signature to flash (DualOptiboot will pick this up and flash it) + uint16_t fwsize = FIRMWARE_BLOCK_SIZE*fc.blocks; + flash.writeBytes(0, "FLXIMG:", 7); + flash.writeByte(7, fwsize >> 8); + flash.writeByte(8, fwsize); + flash.writeByte(9, ':'); + // Write the new firmware config to eeprom + hw_writeConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig)); + hw_reboot(); + } else { + debug(PSTR("fw checksum fail\n")); + } + } + } + // Make sure packet request occurs next time process() is called by timing out requestTime. + fwRetry = MY_OTA_RETRY+1; + fwLastRequestTime = 0; + return false; + } +#endif // Call incoming message callback if available if (msgCallback != NULL) { msgCallback(msg); @@ -613,17 +675,46 @@ void MySensor::wait(unsigned long ms) { } void MySensor::sleep(unsigned long ms) { - radio.powerDown(); - hw.sleep(ms); +#ifdef MY_OTA_FIRMWARE_FEATURE + if (fwUpdateOngoing) { + // Do not sleep node while fw update is ongoing + process(); + } else { +#endif + radio.powerDown(); + hw.sleep(ms); +#ifdef MY_OTA_FIRMWARE_FEATURE + } +#endif } bool MySensor::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { +#ifdef MY_OTA_FIRMWARE_FEATURE + if (fwUpdateOngoing) { + // Do not sleep node while fw update is ongoing + process(); + return false; + } else { +#endif radio.powerDown(); return hw.sleep(interrupt, mode, ms) ; +#ifdef MY_OTA_FIRMWARE_FEATURE + } +#endif } int8_t MySensor::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) { - radio.powerDown(); - return hw.sleep(interrupt1, mode1, interrupt2, mode2, ms) ; +#ifdef MY_OTA_FIRMWARE_FEATURE + if (fwUpdateOngoing) { + // Do not sleep node while fw update is ongoing + process(); + return -1; + } else { +#endif + radio.powerDown(); + return hw.sleep(interrupt1, mode1, interrupt2, mode2, ms) ; +#ifdef MY_OTA_FIRMWARE_FEATURE + } +#endif } diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 40e5cd4..7873c22 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -23,6 +23,9 @@ #include "MySigningNone.h" #endif #include "MyMessage.h" +#ifdef MY_OTA_FIRMWARE_FEATURE +#include "utility/SPIFlash.h" +#endif #include #include @@ -78,6 +81,17 @@ struct ControllerConfig { #define FIRMWARE_BLOCK_SIZE 16 // Number of times a firmware block should be requested before giving up #define FIRMWARE_MAX_REQUESTS 5 +// Number of times to request a fw block before giving up +#define MY_OTA_RETRY 5 +// Number of millisecons before re-request a fw block +#define MY_OTA_RETRY_DELAY 500 +// Start offset for firmware in flash (DualOptiboot wants to keeps a signature first) +#define FIRMWARE_START_OFFSET 10 +// Bootloader version +#define MY_OTA_BOOTLOADER_MAJOR_VERSION 3 +#define MY_OTA_BOOTLOADER_MINOR_VERSION 0 +#define MY_OTA_BOOTLOADER_VERSION (MY_OTA_BOOTLOADER_MINOR_VERSION * 256 + MY_OTA_BOOTLOADER_MAJOR_VERSION) + // FW config structure, stored in eeprom typedef struct { @@ -282,6 +296,11 @@ class MySensor ControllerConfig cc; // Configuration coming from controller #ifdef MY_OTA_FIRMWARE_FEATURE NodeFirmwareConfig fc; + bool fwUpdateOngoing; + unsigned long fwLastRequestTime; + uint16_t fwBlock; + uint8_t fwRetry; + SPIFlash flash; #endif bool repeaterMode; @@ -309,7 +328,7 @@ class MySensor void (*timeCallback)(unsigned long); // Callback for requested time messages void (*msgCallback)(const MyMessage &); // Callback for incoming messages from other nodes and gateway. -#ifdef MY_OTA_FRIMWARE_FEATURE +#ifdef MY_OTA_FIRMWARE_FEATURE // do a crc16 on the whole received firmware bool isValidFirmware(); #endif From 0373b71a03365cd0235c1b5c0093b7446fb18e02 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 30 Mar 2015 11:56:55 +0200 Subject: [PATCH 097/137] Fix Serial GW constructor --- .../MySensors/examples/SerialGateway/SerialGateway.ino | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index 8dc5e26..d103407 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -23,8 +23,9 @@ #define NO_PORTB_PINCHANGES -#include #include +#include + #include #include #include @@ -43,9 +44,11 @@ // NRFRF24L01 radio driver (set low transmit power by default) MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); // Message signing driver (none default) -MySigningNone signer; +//MySigningNone signer; // Construct MySensors library -MySensor gw(radio, signer); +MyHwATMega328 hw; + +MySensor gw(radio, hw); char inputString[MAX_RECEIVE_LENGTH] = ""; // A string to hold incoming commands from serial/ethernet interface int inputPos = 0; From 44406c28351ed8d33875efd650342e0cf0490506 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 30 Mar 2015 22:44:10 +0200 Subject: [PATCH 098/137] Add driver-options to gateways. --- libraries/MySensors/MyConfig.h | 2 +- libraries/MySensors/MySensor.h | 4 ++-- .../EthernetGateway/EthernetGateway.ino | 24 +++++++++++++++---- .../examples/MQTTGateway/MQTTGateway.ino | 24 +++++++++++++++---- .../examples/SerialGateway/SerialGateway.ino | 19 +++++++++++---- 5 files changed, 55 insertions(+), 18 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 4b7b4f1..d4a0633 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -18,7 +18,7 @@ // which requires external flash and the DualOptiBoot bootloader. // Note: You can still have OTA FW updates without external flash but it // requires the MYSBootloader and disabled MY_OTA_FIRMWARE_FEATURE -#define MY_OTA_FIRMWARE_FEATURE +//#define MY_OTA_FIRMWARE_FEATURE // Slave select pin for external flash #define MY_OTA_FLASH_SS 8 // Flash jdecid diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 7873c22..40b44bb 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -31,10 +31,10 @@ // Set the hardware driver to use (initialized by MySensor-class) -#if defined __AVR_ATmega328P__ +//#if defined __AVR_ATmega328P__ #include "MyHwATMega328.h" typedef MyHwATMega328 MyHwDriver; -#endif +//#endif #ifdef DEBUG diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index bde2cf1..81f65f6 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -44,7 +44,12 @@ #include #include +#include #include +#include +#include +#include + #include #include #include @@ -72,11 +77,20 @@ // NRFRF24L01 radio driver (set low transmit power by default) -MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); -// Message signing driver (none default) -MySigningNone signer; -// Construct MySensors library -MySensor gw(radio, signer); +MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +//MyTransportRF69 transport; + +// Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) +//MySigningNone signer; +//MySigningAtsha204Soft signer; +//MySigningAtsha204 signer; + +// Hardware profile +MyHwATMega328 hw; + +// Construct MySensors library (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) +MySensor gw(transport, hw /*, signer*/); + #define IP_PORT 5003 // The port you want to open IPAddress myIp (192, 168, 178, 66); // Configure your static ip-address here COMPILE ERROR HERE? Use Arduino IDE 1.5.7 or later! diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index 169ad89..4742331 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -60,7 +60,12 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway #include #include +#include #include +#include +#include +#include + #include #include #include @@ -94,11 +99,20 @@ uint8_t TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You ////////////////////////////////////////////////////////////////// // NRFRF24L01 radio driver (set low transmit power by default) -MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); -// Message signing driver (none default) -MySigningNone signer; -// Construct MySensors library -MySensor gw(radio, signer); +MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +//MyTransportRF69 transport; + +// Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) +//MySigningNone signer; +//MySigningAtsha204Soft signer; +//MySigningAtsha204 signer; + +// Hardware profile +MyHwATMega328 hw; + +// Construct MySensors library (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) +MySensor gw(transport, hw /*, signer*/); + EthernetServer server = EthernetServer(TCP_PORT); MyMessage msg; diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index d103407..a1b01e4 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -23,8 +23,12 @@ #define NO_PORTB_PINCHANGES +#include +#include #include #include +#include +#include #include #include @@ -40,15 +44,20 @@ #define RADIO_RX_LED_PIN 6 // Receive led pin #define RADIO_TX_LED_PIN 5 // the PCB, on board LED - // NRFRF24L01 radio driver (set low transmit power by default) -MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); -// Message signing driver (none default) +MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +//MyTransportRF69 transport; + +// Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) //MySigningNone signer; -// Construct MySensors library +//MySigningAtsha204Soft signer; +//MySigningAtsha204 signer; + +// Hardware profile MyHwATMega328 hw; -MySensor gw(radio, hw); +// Construct MySensors library (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) +MySensor gw(transport, hw /*, signer*/); char inputString[MAX_RECEIVE_LENGTH] = ""; // A string to hold incoming commands from serial/ethernet interface int inputPos = 0; From 527b2332da1cfffd50e20484fc83badd6ce8ecea Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 31 Mar 2015 23:44:38 +0200 Subject: [PATCH 099/137] Correct initialization for gateway --- libraries/MySensors/MySensor.cpp | 63 ++++++++++++++++---------------- 1 file changed, 31 insertions(+), 32 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 91644e0..70d3680 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -88,56 +88,55 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b msgCallback = _msgCallback; failedTransmissions = 0; - // Only gateway should use node id 0 - isGateway = _nodeId == 0; + // Only gateway should use node id 0! + isGateway = _nodeId == GATEWAY_ADDRESS; // Setup radio radio.init(); - // Read settings from eeprom - hw_readConfigBlock((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); - // Read latest received controller configuration from EEPROM - hw_readConfigBlock((void*)&cc, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS, sizeof(ControllerConfig)); -#ifdef MY_OTA_FIRMWARE_FEATURE - // Read firmware config from EEPROM, i.e. type, version, CRC, blocks - hw_readConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig)); -#endif - - #ifdef MY_SIGNING_FEATURE // Read out the signing requirements from EEPROM hw_readConfigBlock((void*)doSign, (void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, sizeof(doSign)); #endif if (isGateway) { + // Set configuration for gateway + nc.parentNodeId = 0; nc.distance = 0; - } + nc.nodeId = 0; + } else { + // Read settings from eeprom + hw_readConfigBlock((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); + // Read latest received controller configuration from EEPROM + hw_readConfigBlock((void*)&cc, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS, sizeof(ControllerConfig)); +#ifdef MY_OTA_FIRMWARE_FEATURE + // Read firmware config from EEPROM, i.e. type, version, CRC, blocks + hw_readConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig)); +#endif - if (cc.isMetric == 0xff) { - // Eeprom empty, set default to metric - cc.isMetric = 0x01; - } + if (cc.isMetric == 0xff) { + // Eeprom empty, set default to metric + cc.isMetric = 0x01; + } - autoFindParent = _parentNodeId == AUTO; - if (!autoFindParent) { - nc.parentNodeId = _parentNodeId; - // Save static parent id in eeprom (used by bootloader) - hw_writeConfig(EEPROM_PARENT_NODE_ID_ADDRESS, _parentNodeId); - // We don't actually know the distance to gw here. Let's pretend it is 1. - // If the current node is also repeater, be aware of this. - nc.distance = 1; - } else if (!isValidParent(nc.parentNodeId)) { - // Auto find parent, but parent in eeprom is invalid. Try find one. - findParentNode(); - } + autoFindParent = _parentNodeId == AUTO; + if (!autoFindParent) { + nc.parentNodeId = _parentNodeId; + // Save static parent id in eeprom (used by bootloader) + hw_writeConfig(EEPROM_PARENT_NODE_ID_ADDRESS, _parentNodeId); + // We don't actually know the distance to gw here. Let's pretend it is 1. + // If the current node is also repeater, be aware of this. + nc.distance = 1; + } else if (!isValidParent(nc.parentNodeId)) { + // Auto find parent, but parent in eeprom is invalid. Try find one. + findParentNode(); + } - if (!isGateway) { if (_nodeId != AUTO) { // Set static id nc.nodeId = _nodeId; // Save static id in eeprom - if (_nodeId > 0) - hw_writeConfig(EEPROM_NODE_ID_ADDRESS, _nodeId); + hw_writeConfig(EEPROM_NODE_ID_ADDRESS, _nodeId); } else if (isValidParent(nc.parentNodeId)) { // Try to fetch node-id from gateway requestNodeId(); From 6165834038810e46e58f7c56dc890e90875cf861 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 31 Mar 2015 23:46:36 +0200 Subject: [PATCH 100/137] RFM69 cleanup Corrected initialization of radio Add constructor arguments for driver Add defaults to MyConfig Fix ack problems reported on forum. --- libraries/MySensors/MyConfig.h | 29 ++++++++-- libraries/MySensors/MyTransportRF69.cpp | 57 ------------------- libraries/MySensors/MyTransportRF69.h | 44 -------------- libraries/MySensors/MyTransportRFM69.cpp | 54 ++++++++++++++++++ libraries/MySensors/MyTransportRFM69.h | 29 ++++++++++ .../EthernetGateway/EthernetGateway.ino | 4 +- .../examples/MQTTGateway/MQTTGateway.ino | 4 +- .../examples/RelayActuator/RelayActuator.ino | 4 +- .../examples/SerialGateway/SerialGateway.ino | 4 +- 9 files changed, 116 insertions(+), 113 deletions(-) delete mode 100644 libraries/MySensors/MyTransportRF69.cpp delete mode 100644 libraries/MySensors/MyTransportRF69.h create mode 100644 libraries/MySensors/MyTransportRFM69.cpp create mode 100644 libraries/MySensors/MyTransportRFM69.h diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index d4a0633..d274fe0 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -65,11 +65,14 @@ #define RF24_CS_PIN 10 #define RF24_PA_LEVEL RF24_PA_MAX #define RF24_PA_LEVEL_GW RF24_PA_LOW -#define RF24_CHANNEL 76 //RF channel for the sensor net, 0-127 -#define RF24_DATARATE RF24_250KBPS //RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps -#define RF24_BASE_RADIO_ID ((uint64_t)0xA8A8E1FC00LL) // This is also act as base value for sensor nodeId addresses. Change this (or channel) if you have more than one sensor network. +// RF channel for the sensor net, 0-127 +#define RF24_CHANNEL 76 +//RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps +#define RF24_DATARATE RF24_250KBPS +// This is also act as base value for sensor nodeId addresses. Change this (or channel) if you have more than one sensor network. +#define RF24_BASE_RADIO_ID ((uint64_t)0xA8A8E1FC00LL) -// Enable SOFTSPI for the W5100 Ethernet module +// Enable SOFTSPI for NRF24L01 when using the W5100 Ethernet module //#define SOFTSPI #ifdef SOFTSPI // Define the soft SPI pins used for NRF radio @@ -79,4 +82,22 @@ #endif +/********************************** +* RFM69 Driver Defaults +***********************************/ +// Default network id. Use the same for all nodes that will talk to each other +#define RFM69_NETWORKID 100 + +// Default frequency to use. This must match the hardware version of the RFM69 radio (uncomment one): +// #define RFM69_FREQUENCY RF69_433MHZ +#define RFM69_FREQUENCY RF69_868MHZ +//#define FREQUENCY RF69_915MHZ + +// Enable this for encryption of packets +//#define RFM69_ENABLE_ENCRYPTION +#define RFM69_ENCRYPTKEY "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes! + + + + #endif diff --git a/libraries/MySensors/MyTransportRF69.cpp b/libraries/MySensors/MyTransportRF69.cpp deleted file mode 100644 index b55ce14..0000000 --- a/libraries/MySensors/MyTransportRF69.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "MyTransport.h" -#include "MyTransportRF69.h" - -MyTransportRF69::MyTransportRF69() - : - MyTransport(), - radio() -{ -} - -void MyTransportRF69::init() { - // Start up the radio library - radio->initialize(FREQUENCY,_address,NETWORKID); -#ifdef IS_RFM69HW - radio->setHighPower(); //uncomment only for RFM69HW! -#endif - // radio->encrypt(ENCRYPTKEY); - -} - -void MyTransportRF69::setAddress(uint8_t address) { - _address = address; - radio->setAddress(address); -} - -uint8_t MyTransportRF69::getAddress() { - return _address; -} - -bool MyTransportRF69::send(uint8_t to, const void* data, uint8_t len) { - // Make sure radio has powered up - return radio->sendWithRetry(to,data,len); -} - -bool MyTransportRF69::available(uint8_t *to) { - if (radio->TARGETID == BROADCAST_ADDRESS) - *to = BROADCAST_ADDRESS; - else - *to = _address; - return radio->receiveDone(); -} - -uint8_t MyTransportRF69::receive(void* data) { - // for (byte i = 0; i < radio->DATALEN; i++){ - // data[i]= (void)radio->DATA[i]; - // } - memcpy(data,(const void *)radio->DATA, radio->DATALEN); - if (radio->ACKRequested()) - { - radio->sendACK(); - } - return radio->DATALEN; -} - -void MyTransportRF69::powerDown() { - radio->sleep(); -} diff --git a/libraries/MySensors/MyTransportRF69.h b/libraries/MySensors/MyTransportRF69.h deleted file mode 100644 index 687259d..0000000 --- a/libraries/MySensors/MyTransportRF69.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef MyTransportRF69_h -#define MyTransportRF69_h - -#include "MyConfig.h" -#include "MyTransport.h" -#include -#include "utility/RFM69.h" -#include - -#define NODEID 2 //unique for each node on same network -#define NETWORKID 100 //the same on all nodes that talk to each other -#define GATEWAYID 1 -//Match frequency to the hardware version of the radio on your Moteino (uncomment one): -// #define FREQUENCY RF69_433MHZ -#define FREQUENCY RF69_868MHZ -//#define FREQUENCY RF69_915MHZ -#define ENCRYPTKEY "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes! -//#define IS_RFM69HW //uncomment only for RFM69HW! Leave out if you have RFM69W! -#define ACK_TIME 30 // max # of ms to wait for an ack -#ifdef __AVR_ATmega1284P__ - #define LED 15 // Moteino MEGAs have LEDs on D15 - #define FLASH_SS 23 // and FLASH SS on D23 -#else - #define LED 9 // Moteinos have LEDs on D9 - #define FLASH_SS 8 // and FLASH SS on D8 -#endif - -class MyTransportRF69 : public MyTransport -{ -public: - MyTransportRF69(); - void init(); - void setAddress(uint8_t address); - uint8_t getAddress(); - bool send(uint8_t to, const void* data, uint8_t len); - bool available(uint8_t *to); - uint8_t receive(void* data); - void powerDown(); -private: - RFM69 *radio; - uint8_t _address; -}; - -#endif diff --git a/libraries/MySensors/MyTransportRFM69.cpp b/libraries/MySensors/MyTransportRFM69.cpp new file mode 100644 index 0000000..c387816 --- /dev/null +++ b/libraries/MySensors/MyTransportRFM69.cpp @@ -0,0 +1,54 @@ +#include "MyTransport.h" +#include "MyTransportRFM69.h" + +MyTransportRFM69::MyTransportRFM69(uint8_t freqBand, uint8_t networkId, uint8_t slaveSelectPin, uint8_t interruptPin, bool isRFM69HW, uint8_t interruptNum) + : + MyTransport(), + radio(slaveSelectPin, interruptPin, isRFM69HW, interruptNum), + _freqBand(freqBand), + _networkId(networkId) +{ +} + +void MyTransportRFM69::init() { + // Start up the radio library (_address will be set later by the MySensors library) + radio.initialize(_freqBand, _address, _networkId); +#ifdef RFM69_ENABLE_ENCRYPTION + radio.encrypt(ENCRYPTKEY); +#endif + +} + +void MyTransportRFM69::setAddress(uint8_t address) { + _address = address; + radio.setAddress(address); +} + +uint8_t MyTransportRFM69::getAddress() { + return _address; +} + +bool MyTransportRFM69::send(uint8_t to, const void* data, uint8_t len) { + return radio.sendWithRetry(to,data,len); +} + +bool MyTransportRFM69::available(uint8_t *to) { + if (radio.TARGETID == BROADCAST_ADDRESS) + *to = BROADCAST_ADDRESS; + else + *to = _address; + return radio.receiveDone(); +} + +uint8_t MyTransportRFM69::receive(void* data) { + memcpy(data,(const void *)radio.DATA, radio.DATALEN); + // Send ack back if this message wasn't a broadcast + if (radio.TARGETID != RF69_BROADCAST_ADDR) + radio.ACKRequested(); + radio.sendACK(); + return radio.DATALEN; +} + +void MyTransportRFM69::powerDown() { + radio.sleep(); +} diff --git a/libraries/MySensors/MyTransportRFM69.h b/libraries/MySensors/MyTransportRFM69.h new file mode 100644 index 0000000..7b3821a --- /dev/null +++ b/libraries/MySensors/MyTransportRFM69.h @@ -0,0 +1,29 @@ +#ifndef MyTransportRF69_h +#define MyTransportRF69_h + +#include "MyConfig.h" +#include "MyTransport.h" +#include +#include "utility/RFM69.h" +#include + + +class MyTransportRFM69 : public MyTransport +{ +public: + MyTransportRFM69(uint8_t freqBand=RFM69_FREQUENCY, uint8_t networkId=RFM69_NETWORKID, uint8_t slaveSelectPin=RF69_SPI_CS, uint8_t interruptPin=RF69_IRQ_PIN, bool isRFM69HW=false, uint8_t interruptNum=RF69_IRQ_NUM); + void init(); + void setAddress(uint8_t address); + uint8_t getAddress(); + bool send(uint8_t to, const void* data, uint8_t len); + bool available(uint8_t *to); + uint8_t receive(void* data); + void powerDown(); +private: + RFM69 radio; + uint8_t _address; + uint8_t _freqBand; + uint8_t _networkId; +}; + +#endif diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 81f65f6..c653ab4 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -44,7 +44,7 @@ #include #include -#include +#include #include #include #include @@ -78,7 +78,7 @@ // NRFRF24L01 radio driver (set low transmit power by default) MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); -//MyTransportRF69 transport; +//MyTransportRFM69 transport; // Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) //MySigningNone signer; diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index 4742331..006a785 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -60,7 +60,7 @@ http://forum.mysensors.org/topic/303/mqtt-broker-gateway #include #include -#include +#include #include #include #include @@ -100,7 +100,7 @@ uint8_t TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You // NRFRF24L01 radio driver (set low transmit power by default) MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); -//MyTransportRF69 transport; +//MyTransportRFM69 transport; // Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) //MySigningNone signer; diff --git a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino index 615049d..93e93c2 100644 --- a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino +++ b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino @@ -3,7 +3,7 @@ #include #include -//#include +#include #include #include #include @@ -15,7 +15,7 @@ // NRFRF24L01 radio driver (set low transmit power by default) MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); -//MyTransportRF69 radio; +//MyTransportRFM69 radio; // Message signing driver (none default) //MySigningNone signer; // Select AtMega328 hardware profile diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index a1b01e4..266fdb7 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -24,7 +24,7 @@ #define NO_PORTB_PINCHANGES #include -#include +#include #include #include #include @@ -46,7 +46,7 @@ // NRFRF24L01 radio driver (set low transmit power by default) MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); -//MyTransportRF69 transport; +//MyTransportRFM69 transport; // Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) //MySigningNone signer; From 410a8869cbdb59de7923a149d5a43efdc640fc31 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 1 Apr 2015 00:50:25 +0200 Subject: [PATCH 101/137] Add V_UNIT_PREFIX and started documenting variable and sensor types. --- libraries/MySensors/MyMessage.h | 91 ++++++++++++++++++++++++++++----- 1 file changed, 77 insertions(+), 14 deletions(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index 93edc74..e552f13 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -34,16 +34,54 @@ typedef enum { // Type of sensor data (for set/req/ack messages) typedef enum { - V_TEMP,V_HUM, V_LIGHT, V_DIMMER, V_PRESSURE, V_FORECAST, V_RAIN, - V_RAINRATE, V_WIND, V_GUST, V_DIRECTION, V_UV, V_WEIGHT, V_DISTANCE, - V_IMPEDANCE, V_ARMED, V_TRIPPED, V_WATT, V_KWH, V_SCENE_ON, V_SCENE_OFF, - V_HEATER, V_HEATER_SW, V_LIGHT_LEVEL, V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, - V_UP, V_DOWN, V_STOP, V_IR_SEND, V_IR_RECEIVE, V_FLOW, V_VOLUME, V_LOCK_STATUS, - V_DUST_LEVEL, V_VOLTAGE, V_CURRENT, - V_RGB, // Used for sending/receiving color information. Sent as ascii hex. RRGGBB (RR=red, GG=green, BB=blue component) - V_RGBW, // Used for sending/receiving color information. Sent as ascii hex. RRGGBBWW (WW=while component) - V_ID, // Can be used for reporting ids for sensors such as DS1820b. - V_LIGHT_LEVEL_LUX // Light level in lux + V_TEMP, // S_TEMP + V_HUM, // S_HUM + V_LIGHT, // S_LIGHT (Light level in uncalibrated percentage) + V_DIMMER, // S_DIMMER + V_PRESSURE, // S_BARO + V_FORECAST, // S_BARO + V_RAIN, // S_RAIN + V_RAINRATE, // S_RAIN + V_WIND, // S_WIND + V_GUST, // S_WIND + V_DIRECTION, // S_WIND + V_UV, // S_UV + V_WEIGHT, // S_WEIGHT + V_DISTANCE, // S_DISTANCE + V_IMPEDANCE, // S_MULTIMETER, S_WEIGHT + V_ARMED, // S_DOOR, S_MOTION, S_SMOKE, + V_TRIPPED, // S_DOOR, S_MOTION, S_SMOKE, + V_WATT, // S_POWER + V_KWH, // S_POWER + V_SCENE_ON, // S_SCENE_CONTROLLER + V_SCENE_OFF, // S_SCENE_CONTROLLER + V_HEATER, // S_HEATER + V_HEATER_SW, // S_HEATER + V_LIGHT_LEVEL, // S_LIGHT_LEVEL + V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, + V_UP, // S_COVER + V_DOWN, // S_COVER + V_STOP, // S_COVER + V_IR_SEND, // S_IR + V_IR_RECEIVE, // S_IR + V_FLOW, // S_WATER + V_VOLUME, // S_WATER + V_LOCK_STATUS, // S_LOCK + V_DUST_LEVEL, // S_DUST + V_VOLTAGE, // S_MULTIMETER + V_CURRENT, // S_MULTIMETER + V_RGB, // S_RGB_LIGHT, S_COLOR_SENSOR. + // Used for sending color information for led lighting or color sensors. + // Sent as ascii hex. RRGGBB (RR=red, GG=green, BB=blue component) + V_RGBW, // S_RGB_LIGHT + // Used for sending color information to led lighting. + // Sent as ascii hex. RRGGBBWW (WW=while component) + V_ID, // S_TEMP + // Used for reporting the sensor internal ids (E.g. DS1820b). + V_LIGHT_LEVEL_LUX, // S_LIGHT, Light level in lux + V_UNIT_PREFIX // Allows sensors to send in a string representing the + // unit prefix to be displayed in GUI, not parsed! E.g. cm, m, km, inch. + // Can be used for S_DISTANCE } mysensor_data; // Type of internal messages (for internal messages) @@ -56,10 +94,35 @@ typedef enum { // Type of sensor (for presentation message) typedef enum { - S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, - S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, - S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, - S_SCENE_CONTROLLER,S_COLOR, S_MULTIMETER + S_DOOR, + S_MOTION, + S_SMOKE, + S_LIGHT, + S_DIMMER, + S_COVER, + S_TEMP, + S_HUM, + S_BARO, + S_WIND, + S_RAIN, + S_UV, + S_WEIGHT, + S_POWER, + S_HEATER, + S_DISTANCE, + S_LIGHT_LEVEL, + S_ARDUINO_NODE, + S_ARDUINO_REPEATER_NODE, + S_LOCK, + S_IR, + S_WATER, + S_AIR_QUALITY, // V_VAR1 + S_CUSTOM, + S_DUST, // V_DUST_LEVEL + S_SCENE_CONTROLLER, // V_SCENE_ON, V_SCENE_OFF. + S_RGB_LIGHT, // Send data using V_RGB or V_RGBW + S_COLOR_SENSOR, // Send data using V_RGB + S_MULTIMETER // V_VOLTAGE, V_CURRENT, V_IMPEDANCE } mysensor_sensor; // Type of data stream (for streamed message) From be9cb8b1ffd6e57bf03c48fbec83b7aa59f899fc Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 2 Apr 2015 10:10:43 +0200 Subject: [PATCH 102/137] Watchdog Timer interrupt service routine added.Thanks @kolaf. --- libraries/MySensors/MyHwATMega328.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/libraries/MySensors/MyHwATMega328.cpp b/libraries/MySensors/MyHwATMega328.cpp index 4f9d9a8..f7e58a4 100644 --- a/libraries/MySensors/MyHwATMega328.cpp +++ b/libraries/MySensors/MyHwATMega328.cpp @@ -11,6 +11,14 @@ void wakeUp2() //place to send the second interrupts pinIntTrigger = 2; } +// Watchdog Timer interrupt service routine. This routine is required +// to allow automatic WDIF and WDIE bit clearance in hardware. +ISR (WDT_vect) +{ + // WDIE & WDIF is cleared in hardware upon entering this ISR + wdt_disable(); +} + MyHwATMega328::MyHwATMega328() : MyHw() { } From d2dacd8670c94827dfb7b102d9abfd1baa0f235f Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 2 Apr 2015 13:46:54 +0200 Subject: [PATCH 103/137] Fix id request problem at startup --- libraries/MySensors/MySensor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 70d3680..a8e42ea 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -137,7 +137,7 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b nc.nodeId = _nodeId; // Save static id in eeprom hw_writeConfig(EEPROM_NODE_ID_ADDRESS, _nodeId); - } else if (isValidParent(nc.parentNodeId)) { + } else if (nc.nodeId == AUTO && isValidParent(nc.parentNodeId)) { // Try to fetch node-id from gateway requestNodeId(); } From caaadf44cf644b4d0432effaed9130957a75aec6 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 8 Apr 2015 21:14:52 +0200 Subject: [PATCH 104/137] Update file headers. --- libraries/MySensors/MyConfig.h | 20 +++ libraries/MySensors/MyHw.cpp | 19 +++ libraries/MySensors/MyHw.h | 19 +++ libraries/MySensors/MyHwATMega328.cpp | 19 +++ libraries/MySensors/MyHwATMega328.h | 19 +++ libraries/MySensors/MyMessage.cpp | 20 +++ libraries/MySensors/MyMessage.h | 27 ++-- libraries/MySensors/MyParser.cpp | 19 +++ libraries/MySensors/MyParser.h | 21 ++- libraries/MySensors/MyParserSerial.cpp | 19 +++ libraries/MySensors/MyParserSerial.h | 21 ++- libraries/MySensors/MySensor.cpp | 31 ++-- libraries/MySensors/MySensor.h | 27 ++-- libraries/MySensors/MySigning.cpp | 19 +++ libraries/MySensors/MySigning.h | 32 ++++- libraries/MySensors/MySigningAtsha204.cpp | 33 ++++- libraries/MySensors/MySigningAtsha204.h | 33 ++++- libraries/MySensors/MySigningAtsha204Soft.cpp | 39 ++++-- libraries/MySensors/MySigningAtsha204Soft.h | 39 ++++-- libraries/MySensors/MySigningNone.cpp | 32 ++++- libraries/MySensors/MySigningNone.h | 32 ++++- libraries/MySensors/MyTransport.cpp | 19 +++ libraries/MySensors/MyTransport.h | 19 +++ libraries/MySensors/MyTransportNRF24.cpp | 19 +++ libraries/MySensors/MyTransportNRF24.h | 19 +++ libraries/MySensors/MyTransportRFM69.cpp | 19 +++ libraries/MySensors/MyTransportRFM69.h | 19 +++ libraries/MySensors/Version.h | 4 +- .../AirQualitySensor/AirQualitySensor.ino | 52 ++++--- .../BatteryPoweredSensor.ino | 31 +++- .../BinarySwitchSensor/BinarySwitchSensor.ino | 31 +++- .../BinarySwitchSleepSensor.ino | 37 ++++- .../ClearEepromConfig/ClearEepromConfig.ino | 30 +++- .../DallasTemperatureSensor.ino | 27 +++- .../DimmableLEDActuator.ino | 32 +++-- .../examples/DimmableLight/DimmableLight.ino | 27 +++- .../DistanceSensor/DistanceSensor.ino | 28 ++++ .../examples/DustSensor/DustSensor.ino | 57 +++++--- .../EnergyMeterPulseSensor.ino | 43 ++++-- .../EthernetGateway/EthernetGateway.ino | 29 +++- .../examples/EthernetGateway/GatewayUtil.h | 3 +- .../HumiditySensor/HumiditySensor.ino | 29 ++++ .../MySensors/examples/IrSensor/IrSensor.ino | 38 ++++- .../LightLuxSensor/LightLuxSensor.ino | 55 +++++--- .../examples/LightSensor/LightSensor.ino | 28 ++++ .../MAX6875TemperatureSensor.ino | 47 +++++-- .../examples/MQTTGateway/MQTTGateway.ino | 132 ++++++++++-------- .../examples/MotionSensor/MotionSensor.ino | 29 ++++ .../examples/MysensorMicro/MysensorMicro.ino | 39 +++++- .../PressureSensor/PressureSensor.ino | 29 ++++ .../RF433MhzSensor/RF433MhzSensor.ino | 26 +++- .../RFIDLockSensor/RFIDLockSensor.ino | 67 ++++++--- .../RealTimeClockDisplaySensor.ino | 55 ++++++-- .../examples/RelayActuator/RelayActuator.ino | 30 +++- .../RelayWithButtonActuator.ino | 34 ++++- .../examples/RepeaterNode/RepeaterNode.ino | 33 ++++- .../SecretKnockSensor/SecretKnockSensor.ino | 76 ++++++---- .../SecureActuator/SecureActuator.ino | 30 +++- .../examples/SerialGateway/GatewayUtil.h | 24 +++- .../examples/SerialGateway/SerialGateway.ino | 27 +++- .../examples/ServoActuator/ServoActuator.ino | 38 ++++- .../Sha204Personalizer/Sha204Personalizer.ino | 63 ++++++--- .../SoilMoistSensor/SoilMoistSensor.ino | 28 ++++ .../TimeAwareSensor/TimeAwareSensor.ino | 28 +++- .../TouchDisplaySceneControllerSensor.ino | 27 +++- .../MySensors/examples/UVSensor/UVSensor.ino | 55 +++++--- .../WaterMeterPulseSensor.ino | 44 ++++-- 67 files changed, 1795 insertions(+), 401 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index d274fe0..437ef3e 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -1,3 +1,23 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + + #ifndef MyConfig_h #define MyConfig_h #include diff --git a/libraries/MySensors/MyHw.cpp b/libraries/MySensors/MyHw.cpp index 75f020d..3016a6b 100644 --- a/libraries/MySensors/MyHw.cpp +++ b/libraries/MySensors/MyHw.cpp @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #include "MyHw.h" MyHw::MyHw() { diff --git a/libraries/MySensors/MyHw.h b/libraries/MySensors/MyHw.h index 14857c6..74ceb13 100644 --- a/libraries/MySensors/MyHw.h +++ b/libraries/MySensors/MyHw.h @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #ifndef MyHw_h #define MyHw_h diff --git a/libraries/MySensors/MyHwATMega328.cpp b/libraries/MySensors/MyHwATMega328.cpp index f7e58a4..2281e6c 100644 --- a/libraries/MySensors/MyHwATMega328.cpp +++ b/libraries/MySensors/MyHwATMega328.cpp @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #include "MyHw.h" #include "MyHwATMega328.h" diff --git a/libraries/MySensors/MyHwATMega328.h b/libraries/MySensors/MyHwATMega328.h index 8610f1b..ccb35ba 100644 --- a/libraries/MySensors/MyHwATMega328.h +++ b/libraries/MySensors/MyHwATMega328.h @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #ifndef MyHwATMega328_h #define MyHwATMega328_h diff --git a/libraries/MySensors/MyMessage.cpp b/libraries/MySensors/MyMessage.cpp index 7143e9c..a0fab36 100755 --- a/libraries/MySensors/MyMessage.cpp +++ b/libraries/MySensors/MyMessage.cpp @@ -1,3 +1,23 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + + #include "MyMessage.h" #include #include diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index e552f13..c5b8612 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -1,14 +1,23 @@ -/* - The MySensors library adds a new layer on top of the RF24 library. - It handles radio network routing, relaying and ids. - - Created by Henrik Ekblad - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - version 2 as published by the Free Software Foundation. +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. */ + #ifndef MyMessage_h #define MyMessage_h diff --git a/libraries/MySensors/MyParser.cpp b/libraries/MySensors/MyParser.cpp index dacd32b..2011d16 100644 --- a/libraries/MySensors/MyParser.cpp +++ b/libraries/MySensors/MyParser.cpp @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #include "MyParser.h" MyParser::MyParser() { diff --git a/libraries/MySensors/MyParser.h b/libraries/MySensors/MyParser.h index e606a0d..39e2975 100644 --- a/libraries/MySensors/MyParser.h +++ b/libraries/MySensors/MyParser.h @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #ifndef MyParser_h #define MyParser_h @@ -13,4 +32,4 @@ public: // returns true if successfully parsed the input string virtual bool parse(MyMessage &message, char *inputString) = 0; }; -#endif \ No newline at end of file +#endif diff --git a/libraries/MySensors/MyParserSerial.cpp b/libraries/MySensors/MyParserSerial.cpp index 9c1aa88..e2ee52a 100644 --- a/libraries/MySensors/MyParserSerial.cpp +++ b/libraries/MySensors/MyParserSerial.cpp @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #include "MyParser.h" #include "MyParserSerial.h" #include "MyTransport.h" diff --git a/libraries/MySensors/MyParserSerial.h b/libraries/MySensors/MyParserSerial.h index e7baf9b..80d315d 100644 --- a/libraries/MySensors/MyParserSerial.h +++ b/libraries/MySensors/MyParserSerial.h @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #ifndef MyParserSerial_h #define MyParserSerial_h @@ -12,4 +31,4 @@ public: private: uint8_t h2i(char c); }; -#endif \ No newline at end of file +#endif diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index a8e42ea..2f98b9e 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -1,14 +1,23 @@ - /* - The MySensors library adds a new layer on top of the RF24 library. - It handles radio network routing, relaying and ids. - - Created by Henrik Ekblad - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - version 2 as published by the Free Software Foundation. +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. */ + #include "MySensor.h" #define DISTANCE_INVALID (0xFF) @@ -101,9 +110,9 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b if (isGateway) { // Set configuration for gateway - nc.parentNodeId = 0; + nc.parentNodeId = GATEWAY_ADDRESS; nc.distance = 0; - nc.nodeId = 0; + nc.nodeId = GATEWAY_ADDRESS; } else { // Read settings from eeprom hw_readConfigBlock((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 40b44bb..0081b90 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -1,13 +1,22 @@ -/* - The MySensors library adds a new layer on top of the RF24 library. - It handles radio network routing, relaying and ids. +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ - Created by Henrik Ekblad - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - version 2 as published by the Free Software Foundation. -*/ #ifndef MySensor_h #define MySensor_h diff --git a/libraries/MySensors/MySigning.cpp b/libraries/MySensors/MySigning.cpp index 835b947..03c3ee3 100644 --- a/libraries/MySensors/MySigning.cpp +++ b/libraries/MySensors/MySigning.cpp @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #include "MySigning.h" MySigning::MySigning(bool requestSignatures) : _requestSignatures(requestSignatures) { diff --git a/libraries/MySensors/MySigning.h b/libraries/MySensors/MySigning.h index dc4407d..e65d546 100644 --- a/libraries/MySensors/MySigning.h +++ b/libraries/MySensors/MySigning.h @@ -1,9 +1,29 @@ -/* - The MySigning driver provides a generic API for various signing backends to offer - signing of MySensors messages. - - Created by Patrick "Anticimex" Fallberg -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * Signing support created by Patrick "Anticimex" Fallberg + * The MySigning driver provides a generic API for various signing backends to offer + * signing of MySensors messages. + * + */ #ifndef MySigning_h #define MySigning_h diff --git a/libraries/MySensors/MySigningAtsha204.cpp b/libraries/MySensors/MySigningAtsha204.cpp index 07dca5f..2baa0dd 100644 --- a/libraries/MySensors/MySigningAtsha204.cpp +++ b/libraries/MySensors/MySigningAtsha204.cpp @@ -1,9 +1,30 @@ -/* - ATSHA204 signing backend. The Atmel ATSHA204 offers true random number generation and - HMAC-SHA256 authentication with a readout-protected key. - - Created by Patrick "Anticimex" Fallberg -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * Signing support created by Patrick "Anticimex" Fallberg + * ATSHA204 signing backend. The Atmel ATSHA204 offers true random number generation and + * HMAC-SHA256 authentication with a readout-protected key. + * + */ + #include "MySigning.h" #include "MySigningAtsha204.h" diff --git a/libraries/MySensors/MySigningAtsha204.h b/libraries/MySensors/MySigningAtsha204.h index 1ebf386..56342e9 100644 --- a/libraries/MySensors/MySigningAtsha204.h +++ b/libraries/MySensors/MySigningAtsha204.h @@ -1,9 +1,30 @@ -/* - ATSHA204 signing backend. The Atmel ATSHA204 offers true random number generation and - HMAC-SHA256 authentication with a readout-protected key. - - Created by Patrick "Anticimex" Fallberg -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * Signing support created by Patrick "Anticimex" Fallberg + * ATSHA204 signing backend. The Atmel ATSHA204 offers true random number generation and + * HMAC-SHA256 authentication with a readout-protected key. + * + */ + #ifndef MySigningAtsha204_h #define MySigningAtsha204_h diff --git a/libraries/MySensors/MySigningAtsha204Soft.cpp b/libraries/MySensors/MySigningAtsha204Soft.cpp index d5aa8aa..d552c17 100644 --- a/libraries/MySensors/MySigningAtsha204Soft.cpp +++ b/libraries/MySensors/MySigningAtsha204Soft.cpp @@ -1,12 +1,33 @@ -/* - ATSHA204 emulated signing backend. The emulated ATSHA204 implementation offers pseudo random - number generation and HMAC-SHA256 authentication compatible with a "physical" ATSHA204. - NOTE: Key is stored in clear text in the Arduino firmware. Therefore, the use of this back-end - could compromise the key used in the signed message infrastructure if device is lost and its memory - dumped. - - Created by Patrick "Anticimex" Fallberg -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * Signing support created by Patrick "Anticimex" Fallberg + * ATSHA204 emulated signing backend. The emulated ATSHA204 implementation offers pseudo random + * number generation and HMAC-SHA256 authentication compatible with a "physical" ATSHA204. + * NOTE: Key is stored in clear text in the Arduino firmware. Therefore, the use of this back-end + * could compromise the key used in the signed message infrastructure if device is lost and its memory + * dumped. + * + */ + #include "MyConfig.h" #include "MySigning.h" #include "MySigningAtsha204Soft.h" diff --git a/libraries/MySensors/MySigningAtsha204Soft.h b/libraries/MySensors/MySigningAtsha204Soft.h index fdc1371..e516618 100644 --- a/libraries/MySensors/MySigningAtsha204Soft.h +++ b/libraries/MySensors/MySigningAtsha204Soft.h @@ -1,12 +1,33 @@ -/* - ATSHA204 emulated signing backend. The emulated ATSHA204 implementation offers pseudo random - number generation and HMAC-SHA256 authentication compatible with a "physical" ATSHA204. - NOTE: Key is stored in clear text in the Arduino firmware. Therefore, the use of this back-end - could compromise the key used in the signed message infrastructure if device is lost and its memory - dumped. - - Created by Patrick "Anticimex" Fallberg -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * Signing support created by Patrick "Anticimex" Fallberg + * ATSHA204 emulated signing backend. The emulated ATSHA204 implementation offers pseudo random + * number generation and HMAC-SHA256 authentication compatible with a "physical" ATSHA204. + * NOTE: Key is stored in clear text in the Arduino firmware. Therefore, the use of this back-end + * could compromise the key used in the signed message infrastructure if device is lost and its memory + * dumped. + * + */ + #ifndef MySigningHmac256Soft_h #define MySigningHmac256Soft_h diff --git a/libraries/MySensors/MySigningNone.cpp b/libraries/MySensors/MySigningNone.cpp index 93e2aa5..a73a375 100644 --- a/libraries/MySensors/MySigningNone.cpp +++ b/libraries/MySensors/MySigningNone.cpp @@ -1,8 +1,30 @@ -/* - Disabled signing backend. Does not provide any security measures. - - Created by Patrick "Anticimex" Fallberg -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * Signing support created by Patrick "Anticimex" Fallberg + * Disabled signing backend. Does not provide any security measures. + * + */ + + #include "MyConfig.h" #include "MySigning.h" #include "MySigningNone.h" diff --git a/libraries/MySensors/MySigningNone.h b/libraries/MySensors/MySigningNone.h index dd8f319..b024b41 100644 --- a/libraries/MySensors/MySigningNone.h +++ b/libraries/MySensors/MySigningNone.h @@ -1,8 +1,30 @@ -/* - Disabled signing backend. Does not provide any security measures. - - Created by Patrick "Anticimex" Fallberg -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * Signing support created by Patrick "Anticimex" Fallberg + * Disabled signing backend. Does not provide any security measures. + * + */ + + #ifndef MySigningNone_h #define MySigningNone_h diff --git a/libraries/MySensors/MyTransport.cpp b/libraries/MySensors/MyTransport.cpp index 56cfdf9..05627de 100644 --- a/libraries/MySensors/MyTransport.cpp +++ b/libraries/MySensors/MyTransport.cpp @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #include "MyTransport.h" MyTransport::MyTransport() { diff --git a/libraries/MySensors/MyTransport.h b/libraries/MySensors/MyTransport.h index 08ba0c6..839dbbd 100644 --- a/libraries/MySensors/MyTransport.h +++ b/libraries/MySensors/MyTransport.h @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #ifndef MyTransport_h #define MyTransport_h diff --git a/libraries/MySensors/MyTransportNRF24.cpp b/libraries/MySensors/MyTransportNRF24.cpp index 9cc63fb..5635e18 100644 --- a/libraries/MySensors/MyTransportNRF24.cpp +++ b/libraries/MySensors/MyTransportNRF24.cpp @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #include "MyTransport.h" #include "MyTransportNRF24.h" diff --git a/libraries/MySensors/MyTransportNRF24.h b/libraries/MySensors/MyTransportNRF24.h index c5ac75e..5f9b7b7 100644 --- a/libraries/MySensors/MyTransportNRF24.h +++ b/libraries/MySensors/MyTransportNRF24.h @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #ifndef MyTransportNRF24_h #define MyTransportNRF24_h diff --git a/libraries/MySensors/MyTransportRFM69.cpp b/libraries/MySensors/MyTransportRFM69.cpp index c387816..d9b4a9f 100644 --- a/libraries/MySensors/MyTransportRFM69.cpp +++ b/libraries/MySensors/MyTransportRFM69.cpp @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #include "MyTransport.h" #include "MyTransportRFM69.h" diff --git a/libraries/MySensors/MyTransportRFM69.h b/libraries/MySensors/MyTransportRFM69.h index 7b3821a..c564986 100644 --- a/libraries/MySensors/MyTransportRFM69.h +++ b/libraries/MySensors/MyTransportRFM69.h @@ -1,3 +1,22 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + */ + #ifndef MyTransportRF69_h #define MyTransportRF69_h diff --git a/libraries/MySensors/Version.h b/libraries/MySensors/Version.h index 82462b7..437cd2c 100644 --- a/libraries/MySensors/Version.h +++ b/libraries/MySensors/Version.h @@ -1,11 +1,11 @@ /*** * This file defines the Sensor library version number * Normally, contributors should not modify this directly - * as it is manaaged by the MySensors Bot. + * as it is managed by the MySensors Bot. */ #ifndef Version_h #define Version_h -#define LIBRARY_VERSION "1.4.1" +#define LIBRARY_VERSION "1.5 b1" #endif diff --git a/libraries/MySensors/examples/AirQualitySensor/AirQualitySensor.ino b/libraries/MySensors/examples/AirQualitySensor/AirQualitySensor.ino index efe12f3..014ce3d 100644 --- a/libraries/MySensors/examples/AirQualitySensor/AirQualitySensor.ino +++ b/libraries/MySensors/examples/AirQualitySensor/AirQualitySensor.ino @@ -1,20 +1,38 @@ -/* - Vera Arduino MQ2 - - connect the MQ2 sensor as follows : - - A H A >>> 5V - B >>> A0 - H >>> GND - B >>> 10K ohm >>> GND - - Contribution: epierre - Based on http://sandboxelectronics.com/?p=165 - - License: Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) - - Modified by HEK to work in 1.4 -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * + * Connect the MQ2 sensor as follows : + * + * A H A >>> 5V + * B >>> A0 + * H >>> GND + * B >>> 10K ohm >>> GND + * + * Contribution: epierre + * Based on http://sandboxelectronics.com/?p=165 + * License: Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) + * Modified by HEK to work in 1.4 + * + */ #include #include diff --git a/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino b/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino index 97bc0c1..7dbd93b 100644 --- a/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino +++ b/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino @@ -1,6 +1,31 @@ -// This is an example that demonstrates how to report the battery level for a sensor -// Instructions for measuring battery capacity on A0 are available in the follwoing forum -// thread: http://forum.micasaverde.com/index.php/topic,20078.0.html +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * + * This is an example that demonstrates how to report the battery level for a sensor + * Instructions for measuring battery capacity on A0 are available here: + * http://www.mysensors.org/build/battery + * + */ + #include #include diff --git a/libraries/MySensors/examples/BinarySwitchSensor/BinarySwitchSensor.ino b/libraries/MySensors/examples/BinarySwitchSensor/BinarySwitchSensor.ino index 6ca5886..d22b629 100644 --- a/libraries/MySensors/examples/BinarySwitchSensor/BinarySwitchSensor.ino +++ b/libraries/MySensors/examples/BinarySwitchSensor/BinarySwitchSensor.ino @@ -1,6 +1,31 @@ -// Simple binary switch example -// Connect button or door/window reed switch between -// digitial I/O pin 3 (BUTTON_PIN below) and GND. +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * + * Simple binary switch example + * Connect button or door/window reed switch between + * digitial I/O pin 3 (BUTTON_PIN below) and GND. + * http://www.mysensors.org/build/binary + */ + #include #include diff --git a/libraries/MySensors/examples/BinarySwitchSleepSensor/BinarySwitchSleepSensor.ino b/libraries/MySensors/examples/BinarySwitchSleepSensor/BinarySwitchSleepSensor.ino index ff8637a..34e0a17 100644 --- a/libraries/MySensors/examples/BinarySwitchSleepSensor/BinarySwitchSleepSensor.ino +++ b/libraries/MySensors/examples/BinarySwitchSleepSensor/BinarySwitchSleepSensor.ino @@ -1,9 +1,34 @@ -// Interrupt driven binary switch example with dual interrupts -// Author: Patrick 'Anticimex' Fallberg -// Connect one button or door/window reed switch between -// digitial I/O pin 3 (BUTTON_PIN below) and GND and the other -// one in similar fashion on digital I/O pin 2. -// This example is designed to fit Arduino Nano/Pro Mini +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * + * Interrupt driven binary switch example with dual interrupts + * Author: Patrick 'Anticimex' Fallberg + * Connect one button or door/window reed switch between + * digitial I/O pin 3 (BUTTON_PIN below) and GND and the other + * one in similar fashion on digital I/O pin 2. + * This example is designed to fit Arduino Nano/Pro Mini + * + */ + #include #include diff --git a/libraries/MySensors/examples/ClearEepromConfig/ClearEepromConfig.ino b/libraries/MySensors/examples/ClearEepromConfig/ClearEepromConfig.ino index ddbaaba..ae8debf 100644 --- a/libraries/MySensors/examples/ClearEepromConfig/ClearEepromConfig.ino +++ b/libraries/MySensors/examples/ClearEepromConfig/ClearEepromConfig.ino @@ -1,8 +1,28 @@ -/* -* -* This sketch clears radioId, relayId and routing info in EEPROM -* -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * + * This sketch clears radioId, relayId and other routing information in EEPROM back to factory default + * + */ #include #include diff --git a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino index 3c6c2c0..5ac41b4 100644 --- a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino @@ -1,4 +1,29 @@ -// Example sketch showing how to send in OneWire temperature readings +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * DESCRIPTION + * + * Example sketch showing how to send in DS1820B OneWire temperature readings back to the controller + * http://www.mysensors.org/build/temp + */ + #include #include #include diff --git a/libraries/MySensors/examples/DimmableLEDActuator/DimmableLEDActuator.ino b/libraries/MySensors/examples/DimmableLEDActuator/DimmableLEDActuator.ino index 6c6a140..d0ecb92 100644 --- a/libraries/MySensors/examples/DimmableLEDActuator/DimmableLEDActuator.ino +++ b/libraries/MySensors/examples/DimmableLEDActuator/DimmableLEDActuator.ino @@ -1,8 +1,27 @@ -/*** +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. - * + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - February 15, 2014 - Bruce Lacey + * Version 1.1 - August 13, 2014 - Converted to 1.4 (hek) + * * DESCRIPTION * This sketch provides a Dimmable LED Light using PWM and based Henrik Ekblad * Vera Arduino Sensor project. @@ -13,12 +32,9 @@ * to the LED negative terminal and the MOSFET Source pin is connected to ground. * * This sketch is extensible to support more than one MOSFET/PWM dimmer per circuit. - * - * REVISION HISTORY - * Version 1.0 - February 15, 2014 - Bruce Lacey - * Version 1.1 - August 13, 2014 - Converted to 1.4 (hek) - * - ***/ + * http://www.mysensors.org/build/dimmer + */ + #define SN "DimmableLED" #define SV "1.1" diff --git a/libraries/MySensors/examples/DimmableLight/DimmableLight.ino b/libraries/MySensors/examples/DimmableLight/DimmableLight.ino index d396d37..d2e0812 100644 --- a/libraries/MySensors/examples/DimmableLight/DimmableLight.ino +++ b/libraries/MySensors/examples/DimmableLight/DimmableLight.ino @@ -1,7 +1,25 @@ -/*** +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - January 30, 2015 - Developed by GizMoCuz (Domoticz) * * DESCRIPTION * This sketch provides an example how to implement a Dimmable Light @@ -9,12 +27,7 @@ * It can be used as a base sketch for actual hardware. * Stores the last light state and level in eeprom. * - * Developed by GizMoCuz (Domoticz) - * - * REVISION HISTORY - * Version 1.0 - January 30, 2015 - * - ***/ + */ #include #include diff --git a/libraries/MySensors/examples/DistanceSensor/DistanceSensor.ino b/libraries/MySensors/examples/DistanceSensor/DistanceSensor.ino index abd0530..a21e86a 100644 --- a/libraries/MySensors/examples/DistanceSensor/DistanceSensor.ino +++ b/libraries/MySensors/examples/DistanceSensor/DistanceSensor.ino @@ -1,3 +1,31 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik EKblad + * + * DESCRIPTION + * This sketch provides an example how to implement a distance sensor using HC-SR04 + * http://www.mysensors.org/build/distance + */ + #include #include #include diff --git a/libraries/MySensors/examples/DustSensor/DustSensor.ino b/libraries/MySensors/examples/DustSensor/DustSensor.ino index 4ebe804..38f6682 100644 --- a/libraries/MySensors/examples/DustSensor/DustSensor.ino +++ b/libraries/MySensors/examples/DustSensor/DustSensor.ino @@ -1,21 +1,42 @@ -/* - Arduino Dust Sensort - - connect the sensor as follows : - - VCC >>> 5V - A >>> A0 - GND >>> GND - - Based on: http://www.dfrobot.com/wiki/index.php/Sharp_GP2Y1010AU - Authors: Cyrille Médard de Chardon (serialC), Christophe Trefois (Trefex) - Contribution: epierre - COnverted to 1.4 by Henrik Ekblad - - The dust sensor used (see purchase guide for latest link): - http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=2&pub=5575069610&toolid=10001&campid=5337433187&customid=&icep_item=171259125886&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg - -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - epierre + * Converted to 1.4 by Henrik Ekblad + * + * DESCRIPTION + * Arduino Dust Sensort + * + * connect the sensor as follows : + * + * VCC >>> 5V + * A >>> A0 + * GND >>> GND + * + * Based on: http://www.dfrobot.com/wiki/index.php/Sharp_GP2Y1010AU + * Authors: Cyrille Médard de Chardon (serialC), Christophe Trefois (Trefex) + * + * http://www.mysensors.org/build/dust + * + */ #include #include diff --git a/libraries/MySensors/examples/EnergyMeterPulseSensor/EnergyMeterPulseSensor.ino b/libraries/MySensors/examples/EnergyMeterPulseSensor/EnergyMeterPulseSensor.ino index 01f3e66..b146a3b 100644 --- a/libraries/MySensors/examples/EnergyMeterPulseSensor/EnergyMeterPulseSensor.ino +++ b/libraries/MySensors/examples/EnergyMeterPulseSensor/EnergyMeterPulseSensor.ino @@ -1,11 +1,38 @@ -// Use this sensor to measure KWH and Watt of your house meeter -// You need to set the correct pulsefactor of your meeter (blinks per KWH). -// The sensor starts by fetching current KWH value from gateway. -// Reports both KWH and Watt back to gateway. -// -// Unfortunately millis() won't increment when the Arduino is in -// sleepmode. So we cannot make this sensor sleep if we also want -// to calculate/report watt-number. +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik EKblad + * + * DESCRIPTION + * This sketch provides an example how to implement a distance sensor using HC-SR04 + * Use this sensor to measure KWH and Watt of your house meeter + * You need to set the correct pulsefactor of your meeter (blinks per KWH). + * The sensor starts by fetching current KWH value from gateway. + * Reports both KWH and Watt back to gateway. + * + * Unfortunately millis() won't increment when the Arduino is in + * sleepmode. So we cannot make this sensor sleep if we also want + * to calculate/report watt-number. + * http://www.mysensors.org/build/pulse_power + */ #include #include diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index c653ab4..562b28d 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -1,13 +1,28 @@ - -/* - * Copyright (C) 2013 Henrik Ekblad - * - * Contribution by a-lurker and Anticimex, - * Contribution by Norbert Truchsess +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik EKblad + * Contribution by a-lurker and Anticimex, + * Contribution by Norbert Truchsess + * * * DESCRIPTION * The EthernetGateway sends data received from sensors to the ethernet link. @@ -35,7 +50,7 @@ * - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly * - ERR (red) - fast blink on error during transmission error or recieve crc error * - * See http://www.mysensors.org/build/ethernet_gateway for wiring instructions. + * See http://www.mysensors.org/build/ethernet_gateway for wiring instructions. * */ #define NO_PORTB_PINCHANGES diff --git a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h index 6f006df..2c1b22c 100644 --- a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h @@ -133,7 +133,7 @@ void parseAndSend(MySensor gw, char *commandBuffer) { } void setInclusionMode(boolean newMode) { - if (newMode != inclusionMode) + if (newMode != inclusionMode) { inclusionMode = newMode; // Send back mode change on serial line to ack command serial(PSTR("0;0;%d;0;%d;%d\n"), C_INTERNAL, I_INCLUSION_MODE, inclusionMode?1:0); @@ -141,6 +141,7 @@ void setInclusionMode(boolean newMode) { if (inclusionMode) { inclusionStartTime = millis(); } + } } diff --git a/libraries/MySensors/examples/HumiditySensor/HumiditySensor.ino b/libraries/MySensors/examples/HumiditySensor/HumiditySensor.ino index 54dc5eb..f5020cd 100644 --- a/libraries/MySensors/examples/HumiditySensor/HumiditySensor.ino +++ b/libraries/MySensors/examples/HumiditySensor/HumiditySensor.ino @@ -1,3 +1,32 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik EKblad + * + * DESCRIPTION + * This sketch provides an example how to implement a humidity/temperature + * sensor using DHT11/DHT-22 + * http://www.mysensors.org/build/humidity + */ + #include #include #include diff --git a/libraries/MySensors/examples/IrSensor/IrSensor.ino b/libraries/MySensors/examples/IrSensor/IrSensor.ino index e954fcd..6c8d87e 100644 --- a/libraries/MySensors/examples/IrSensor/IrSensor.ino +++ b/libraries/MySensors/examples/IrSensor/IrSensor.ino @@ -1,9 +1,35 @@ -// Example sketch showing how to control ir devices -// An IR LED must be connected to Arduino PWM pin 3. -// An optional ir receiver can be connected to PWM pin 8. -// All receied ir signals will be sent to gateway device stored in VAR_1. -// When binary light on is clicked - sketch will send volume up ir command -// When binary light off is clicked - sketch will send volume down ir command +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik EKblad + * + * DESCRIPTION + * Example sketch showing how to control ir devices + * An IR LED must be connected to Arduino PWM pin 3. + * An optional ir receiver can be connected to PWM pin 8. + * All receied ir signals will be sent to gateway device stored in VAR_1. + * When binary light on is clicked - sketch will send volume up ir command + * When binary light off is clicked - sketch will send volume down ir command + * http://www.mysensors.org/build/ir + */ #include #include diff --git a/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino b/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino index 2896056..2b57de3 100644 --- a/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino +++ b/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino @@ -1,20 +1,41 @@ -/* - Vera Arduino BH1750FVI Light sensor - communicate using I2C Protocol - this library enable 2 slave device addresses - Main address 0x23 - secondary address 0x5C - connect the sensor as follows : - - VCC >>> 5V - Gnd >>> Gnd - ADDR >>> NC or GND - SCL >>> A5 - SDA >>> A4 - - Contribution: idefix - -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - idefix + * + * DESCRIPTION + * Arduino BH1750FVI Light sensor + * communicate using I2C Protocol + * this library enable 2 slave device addresses + * Main address 0x23 + * secondary address 0x5C + * connect the sensor as follows : + * + * VCC >>> 5V + * Gnd >>> Gnd + * ADDR >>> NC or GND + * SCL >>> A5 + * SDA >>> A4 + * http://www.mysensors.org/build/light + */ #include #include diff --git a/libraries/MySensors/examples/LightSensor/LightSensor.ino b/libraries/MySensors/examples/LightSensor/LightSensor.ino index 534f8bb..b63c96b 100644 --- a/libraries/MySensors/examples/LightSensor/LightSensor.ino +++ b/libraries/MySensors/examples/LightSensor/LightSensor.ino @@ -1,3 +1,31 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik EKblad + * + * DESCRIPTION + * Example sketch showing how to measue light level using a LM393 photo-resistor + * http://www.mysensors.org/build/light + */ + #include #include diff --git a/libraries/MySensors/examples/MAX6875TemperatureSensor/MAX6875TemperatureSensor.ino b/libraries/MySensors/examples/MAX6875TemperatureSensor/MAX6875TemperatureSensor.ino index 553b840..d153c24 100644 --- a/libraries/MySensors/examples/MAX6875TemperatureSensor/MAX6875TemperatureSensor.ino +++ b/libraries/MySensors/examples/MAX6875TemperatureSensor/MAX6875TemperatureSensor.ino @@ -1,14 +1,39 @@ -// MAX6875 Hight temperature sensor with range: -200 degC - +1300 degC -// Contribution by MrLynx -// http://forum.mysensors.org/topic/641/max6675 -// -// Connect: -// MAX6675 - Arduino -// CS0 - 4 -// SO - 3 -// SCLK - 5 -// VCC - 5V -// GND - GND +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - MrLynx + * + * DESCRIPTION + * MAX6875 High temperature sensor with range: -200 degC - +1300 degC + * http://forum.mysensors.org/topic/641/max6675 + * + * Connect MAX6675 - Arduino + * CS0 - 4 + * SO - 3 + * SCLK - 5 + * VCC - 5V + * GND - GND + * + */ + #include #include diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index 24e25eb..867c8be 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -1,60 +1,78 @@ -/* MyMQTT Broker Gateway 0.1b - -Created by Daniel Wiegert -Based on MySensors Ethernet Gateway by Henrik Ekblad -http://www.mysensors.org - -Requires MySensors lib 1.4b - -* Change below; TCP_IP, TCP_PORT, TCP_MAC -This will listen on your selected TCP_IP:TCP_PORT below, Please change TCP_MAC your liking also. -*1 -> NOTE: Keep first byte at x2, x6, xA or xE (replace x with any hex value) for using Local Ranges. - -*2 You can use standard pin set-up as MySensors recommends or if you own a IBOARD you may change - the radio-pins below if you hardware mod your iBoard. see [URL BELOW] for more details. - http://forum.mysensors.org/topic/224/iboard-cheap-single-board-ethernet-arduino-with-radio/5 - -* Don't forget to look at the definitions in libraries\MySensors\MyMQTT.h! - - define TCPDUMP and connect serial interface if you have problems, please write on - http://forum.mysensors.org/ and explain your problem, include serial output. Don't forget to - turn on DEBUG in libraries\MySensors\MyConfig.h also. - - MQTT_FIRST_SENSORID is for 'DHCP' server in MyMQTT. You may limit the ID's with FIRST and LAST definition. - If you want your manually configured below 20 set MQTT_FIRST_SENSORID to 20. - To disable: set MQTT_FIRST_SENSORID to 255. - - MQTT_BROKER_PREFIX is the leading prefix for your nodes. This can be only one char if like. - - MQTT_SEND_SUBSCRIPTION is if you want the MyMQTT to send a empty payload message to your nodes. - This can be useful if you want to send latest state back to the MQTT client. Just check if incoming - message has any length or not. - Example: if (msg.type==V_LIGHT && strlen(msg.getString())>0) otherwise the code might do strange things. - -* Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/V_[SensorType] - NodeID and SensorID is uint8 (0-255) number. - Last segment is translation of the sensor type, look inside MyMQTT.cpp for the definitions. - User can change this to their needs. We have also left some space for custom types. - -Special: (sensor 255 reserved for special commands) -You can receive a node sketch name with MyMQTT/20/255/V_Sketch_name (or version with _version) - -To-do: -Special commands : clear or set EEPROM Values, Send REBOOT and Receive reboot for MyMQTT itself. -Be able to send ACK so client returns the data being sent. -... Please come with ideas! -What to do with publish messages. - -Test in more MQTT clients, So far tested in openhab and MyMQTT for Android (Not my creation) -- http://www.openhab.org/ -- https://play.google.com/store/apps/details?id=at.tripwire.mqtt.client&hl=en -... Please notify me if you use this broker with other software. - - -* How to set-up Openhab and MQTTGateway: -http://forum.mysensors.org/topic/303/mqtt-broker-gateway - -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Created by Daniel Wiegert + * + * DESCRIPTION + * MyMQTT Broker Gateway 0.1b + * Latest instructions found here: + * http://www.mysensors.org/build/mqtt_gateway + * http://www.mysensors.org/build/ethernet_gateway + * + * Change below; TCP_IP, TCP_PORT, TCP_MAC + * This will listen on your selected TCP_IP:TCP_PORT below, Please change TCP_MAC your liking also. + * 1 -> NOTE: Keep first byte at x2, x6, xA or xE (replace x with any hex value) for using Local Ranges. + * 2 You can use standard pin set-up as MySensors recommends or if you own a IBOARD you may change + * the radio-pins below if you hardware mod your iBoard. see [URL BELOW] for more details. + * http://forum.mysensors.org/topic/224/iboard-cheap-single-board-ethernet-arduino-with-radio/5 + * + * Don't forget to look at the definitions in MyMQTT.h! + * + * define TCPDUMP and connect serial interface if you have problems, please write on + * http://forum.mysensors.org/ and explain your problem, include serial output. Don't forget to + * turn on DEBUG in libraries\MySensors\MyConfig.h also. + * + * MQTT_FIRST_SENSORID is for 'DHCP' server in MyMQTT. You may limit the ID's with FIRST and LAST definition. + * If you want your manually configured below 20 set MQTT_FIRST_SENSORID to 20. + * To disable: set MQTT_FIRST_SENSORID to 255. + * + * MQTT_BROKER_PREFIX is the leading prefix for your nodes. This can be only one char if like. + * + * MQTT_SEND_SUBSCRIPTION is if you want the MyMQTT to send a empty payload message to your nodes. + * This can be useful if you want to send latest state back to the MQTT client. Just check if incoming + * message has any length or not. + * Example: if (msg.type==V_LIGHT && strlen(msg.getString())>0) otherwise the code might do strange things. + * + * (*) Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/V_[SensorType] + * NodeID and SensorID is uint8 (0-255) number. + * Last segment is translation of the sensor type, look inside MyMQTT.cpp for the definitions. + * User can change this to their needs. We have also left some space for custom types. + * + * Special: (sensor 255 reserved for special commands) + * You can receive a node sketch name with MyMQTT/20/255/V_Sketch_name (or version with _version) + * + * To-do: + * Special commands : clear or set EEPROM Values, Send REBOOT and Receive reboot for MyMQTT itself. + * Be able to send ACK so client returns the data being sent. + * ... Please come with ideas! + * What to do with publish messages. + * + * Test in more MQTT clients, So far tested in openhab and MyMQTT for Android (Not my creation) + * - http://www.openhab.org/ + * - https://play.google.com/store/apps/details?id=at.tripwire.mqtt.client&hl=en + * ... Please notify me if you use this broker with other software. + * + * How to set-up Openhab and MQTTGateway: + * http://forum.mysensors.org/topic/303/mqtt-broker-gateway + */ #include #include diff --git a/libraries/MySensors/examples/MotionSensor/MotionSensor.ino b/libraries/MySensors/examples/MotionSensor/MotionSensor.ino index db8373f..0c9179b 100644 --- a/libraries/MySensors/examples/MotionSensor/MotionSensor.ino +++ b/libraries/MySensors/examples/MotionSensor/MotionSensor.ino @@ -1,3 +1,32 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * Motion Sensor example using HC-SR501 + * http://www.mysensors.org/build/motion + * + */ + #include #include diff --git a/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino b/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino index c25fac2..9f98b3e 100644 --- a/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino +++ b/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino @@ -1,9 +1,36 @@ -// Default sensor sketch for MySensor Micro module -// Act as a temperature / humidity sensor by default. -// -// If A0 is held low while powering on, it will enter testmode, which verifies all on-board peripherals -// -// Battery voltage is repported as child sensorId 199, as well as battery percentage +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Thomas Bowman Mørch + * + * DESCRIPTION + * Default sensor sketch for MySensor Sensebender Micro module + * Act as a temperature / humidity sensor by default. + * + * If A0 is held low while powering on, it will enter testmode, which verifies all on-board peripherals + * + * Battery voltage is repported as child sensorId 199, as well as battery percentage + * + */ + #include diff --git a/libraries/MySensors/examples/PressureSensor/PressureSensor.ino b/libraries/MySensors/examples/PressureSensor/PressureSensor.ino index c5743e6..4c8ff9b 100644 --- a/libraries/MySensors/examples/PressureSensor/PressureSensor.ino +++ b/libraries/MySensors/examples/PressureSensor/PressureSensor.ino @@ -1,3 +1,32 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * Pressure sensor example using BMP085 module + * http://www.mysensors.org/build/pressure + * + */ + #include #include #include diff --git a/libraries/MySensors/examples/RF433MhzSensor/RF433MhzSensor.ino b/libraries/MySensors/examples/RF433MhzSensor/RF433MhzSensor.ino index 682e4d7..ec21834 100644 --- a/libraries/MySensors/examples/RF433MhzSensor/RF433MhzSensor.ino +++ b/libraries/MySensors/examples/RF433MhzSensor/RF433MhzSensor.ino @@ -1,4 +1,27 @@ -/* +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION * This sketch demonstrates how to use InterruptChain to receive and * decode remote switches (old and new) and remote sensors. * @@ -15,7 +38,6 @@ * Setup: * - connect a 433MHz receiver on digital pin 2. * - * * MySensor note: This example has not yet been adopted but can be used as an example * of receiving 433Mhz stuff. * diff --git a/libraries/MySensors/examples/RFIDLockSensor/RFIDLockSensor.ino b/libraries/MySensors/examples/RFIDLockSensor/RFIDLockSensor.ino index ecb9756..7b0880c 100644 --- a/libraries/MySensors/examples/RFIDLockSensor/RFIDLockSensor.ino +++ b/libraries/MySensors/examples/RFIDLockSensor/RFIDLockSensor.ino @@ -1,26 +1,47 @@ -/* - RFID Lock sensor/actuator - - Henrik Ekblad - - Use RFID tag to lock/unlock a door or trigger a scene on your controller. - This example sketch allows you to add an optional relay or solenoid - which can be activated/opened by RFID or controller. - - Use the I2C wiring option for your RFID module and connect to the following Arduino pins. - - RFID Arduino - ----- ------- - GND -> GND - VCC -> +5V - SCL -> A5 - SDA -> A4 - - Use normal wiring for NRF24L01 radio - - Attach a optional relay or solonoid lock to pin 4 - -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * RFID Lock sensor/actuator + * + * Use RFID tag to lock/unlock a door or trigger a scene on your controller. + * This example sketch allows you to add an optional relay or solenoid + * which can be activated/opened by RFID or controller. + * + * Use the I2C wiring option for your RFID module and connect to the following Arduino pins. + * + * RFID Arduino + * ----- ------- + * GND -> GND + * VCC -> +5V + * SCL -> A5 + * SDA -> A4 + * + * Use normal wiring for NRF24L01 radio + * + * Attach a optional relay or solonoid lock to pin 4 + * http://www.mysensors.org/build/rfid + */ #include #include diff --git a/libraries/MySensors/examples/RealTimeClockDisplaySensor/RealTimeClockDisplaySensor.ino b/libraries/MySensors/examples/RealTimeClockDisplaySensor/RealTimeClockDisplaySensor.ino index 32e17fa..a4c5944 100644 --- a/libraries/MySensors/examples/RealTimeClockDisplaySensor/RealTimeClockDisplaySensor.ino +++ b/libraries/MySensors/examples/RealTimeClockDisplaySensor/RealTimeClockDisplaySensor.ino @@ -1,18 +1,43 @@ - -// Example sketch showing how to request time from controller which is stored in RTC module -// The time and temperature (DS3231/DS3232) is shown on an attached Crystal LCD display -// -// Created by Henrik Ekblad -// Inspired by Gregl - -// Wiring (radio wiring on www.mysensors.org) -// ------------------------------------ -// Arduino RTC-Module I2C Display -// ------------------------------------ -// GND GND GND -// +5V VCC VCC -// A4 SDA SDA -// A5 SCL SCL +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * Example sketch showing how to request time from controller which is stored in RTC module + * The time and temperature (DS3231/DS3232) is shown on an attached Crystal LCD display + * + * + * Wiring (radio wiring on www.mysensors.org) + * ------------------------------------ + * Arduino RTC-Module I2C Display + * ------------------------------------ + * GND GND GND + * +5V VCC VCC + * A4 SDA SDA + * A5 SCL SCL + * + * http://www.mysensors.org/build/display + * + */ #include diff --git a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino index 93e93c2..db05836 100644 --- a/libraries/MySensors/examples/RelayActuator/RelayActuator.ino +++ b/libraries/MySensors/examples/RelayActuator/RelayActuator.ino @@ -1,5 +1,31 @@ -// Example sketch showing how to control physical relays. -// This example will remember relay state even after power failure. +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * Example sketch showing how to control physical relays. + * This example will remember relay state after power failure. + * http://www.mysensors.org/build/relay + */ #include #include diff --git a/libraries/MySensors/examples/RelayWithButtonActuator/RelayWithButtonActuator.ino b/libraries/MySensors/examples/RelayWithButtonActuator/RelayWithButtonActuator.ino index 7cc2a77..07781d6 100644 --- a/libraries/MySensors/examples/RelayWithButtonActuator/RelayWithButtonActuator.ino +++ b/libraries/MySensors/examples/RelayWithButtonActuator/RelayWithButtonActuator.ino @@ -1,7 +1,33 @@ -// Example sketch för a "light switch" where you can control light or something -// else from both vera and a local physical button (connected between digital -// pin 3 and GND). -// This node also works as a repeader for other nodes +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * Example sketch for a "light switch" where you can control light or something + * else from both HA controller and a local physical button + * (connected between digital pin 3 and GND). + * This node also works as a repeader for other nodes + * http://www.mysensors.org/build/relay + */ #include #include diff --git a/libraries/MySensors/examples/RepeaterNode/RepeaterNode.ino b/libraries/MySensors/examples/RepeaterNode/RepeaterNode.ino index 8ada2de..223f29b 100644 --- a/libraries/MySensors/examples/RepeaterNode/RepeaterNode.ino +++ b/libraries/MySensors/examples/RepeaterNode/RepeaterNode.ino @@ -1,7 +1,32 @@ -// Example sketch showing how to create a node thay repeates messages -// from nodes far from gateway back to gateway. -// It is important that nodes that has enabled repeater mode calls -// gw.preocess() frequently. This node should never sleep. +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * Example sketch showing how to create a node thay repeates messages + * from nodes far from gateway back to gateway. + * It is important that nodes that has enabled repeater mode calls + * gw.process() frequently. Repeaters should never sleep. + */ #include #include diff --git a/libraries/MySensors/examples/SecretKnockSensor/SecretKnockSensor.ino b/libraries/MySensors/examples/SecretKnockSensor/SecretKnockSensor.ino index 9f5f00f..ec2a4ef 100644 --- a/libraries/MySensors/examples/SecretKnockSensor/SecretKnockSensor.ino +++ b/libraries/MySensors/examples/SecretKnockSensor/SecretKnockSensor.ino @@ -1,28 +1,54 @@ -/* Secret Knock Sensor - - See original instructions here (note: The MySensors adopted code might differ in wiring. The instructions below is correct): - https://learn.adafruit.com/secret-knock-activated-drawer-lock/ - Version 13.10.31 Built with Arduino IDE 1.0.5 - - By Steve Hoefer http://grathio.com - Adapted to MySensors by Henrik Ekblad - - Licensed under Creative Commons Attribution-Noncommercial-Share Alike 3.0 - http://creativecommons.org/licenses/by-nc-sa/3.0/us/ - (In short: Do what you want, as long as you credit me, don't relicense it, and don't sell it or use it in anything you sell without contacting me.) - - ------Wiring------ - Pin 0: Program button used for recording a new Knock (connect Pin0 -> button -> GND) - Pin 1: Optional: Connect LED here (remember resisor in series) - Pin 2: Optional: Piezo element (for beeps). - Pin 5: A sound sensor (digital output) for sensing knocks. See MySensors purchase guide. I used this: http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=2&pub=5575069610&toolid=10001&campid=5337433187&customid=&icep_item=200941260251&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg - Pin 4: Connects to either 1. Relay which open door or lock or - 2. transistor that opens a solenoid lock when HIGH (see adafruit guide for this option). - - - Connect radio according as usual(you can skip IRQ pin) - http://www.mysensors.org/build/connect_radio -*/ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * + * Secret Knock Sensor + * http://www.mysensors.org/build/knock + * + * See original instructions here (note: The MySensors adopted code might differ in wiring. The instructions below is correct): + * https://learn.adafruit.com/secret-knock-activated-drawer-lock/ + * Version 13.10.31 Built with Arduino IDE 1.0.5 + * + * By Steve Hoefer http://grathio.com + * Adapted to MySensors by Henrik Ekblad + * + * Licensed under Creative Commons Attribution-Noncommercial-Share Alike 3.0 + * http://creativecommons.org/licenses/by-nc-sa/3.0/us/ + * (In short: Do what you want, as long as you credit me, don't relicense it, and don't sell it or use it in anything you sell without contacting me.) + * + * ------Wiring------ + * Pin 0: Program button used for recording a new Knock (connect Pin0 -> button -> GND) + * Pin 1: Optional: Connect LED here (remember resisor in series) + * Pin 2: Optional: Piezo element (for beeps). + * Pin 5: A sound sensor (digital output) for sensing knocks. See MySensors purchase guide. I used this: http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=2&pub=5575069610&toolid=10001&campid=5337433187&customid=&icep_item=200941260251&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg + * Pin 4: Connects to either 1. Relay which open door or lock or + * 2. transistor that opens a solenoid lock when HIGH (see adafruit guide for this option). + * + * + * Connect radio according as usual(you can skip IRQ pin) + * http://www.mysensors.org/build/connect_radio + */ #include #include diff --git a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino index 73bf57d..cae4b81 100644 --- a/libraries/MySensors/examples/SecureActuator/SecureActuator.ino +++ b/libraries/MySensors/examples/SecureActuator/SecureActuator.ino @@ -1,5 +1,31 @@ -// Example sketch showing how to securely control locks. -// This example will remember lock state even after power failure. +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Patrick "Anticimex" Fallberg + * + * DESCRIPTION + * Example sketch showing how to securely control locks. + * This example will remember lock state even after power failure. + */ + #define USE_SOFTWARE_ATSHA // Disable to use ATSHA204A circuit diff --git a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h index 6f006df..532d9ca 100644 --- a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h @@ -1,3 +1,23 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + */ + #ifndef __GATEWAYUTIL_H__ #define __GATEWAYUTIL_H__ @@ -133,7 +153,7 @@ void parseAndSend(MySensor gw, char *commandBuffer) { } void setInclusionMode(boolean newMode) { - if (newMode != inclusionMode) + if (newMode != inclusionMode) { inclusionMode = newMode; // Send back mode change on serial line to ack command serial(PSTR("0;0;%d;0;%d;%d\n"), C_INTERNAL, I_INCLUSION_MODE, inclusionMode?1:0); @@ -141,6 +161,7 @@ void setInclusionMode(boolean newMode) { if (inclusionMode) { inclusionStartTime = millis(); } + } } @@ -193,3 +214,4 @@ void errBlink(uint8_t cnt) { #endif // ARDUINO #endif + diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index 266fdb7..9bfa910 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -1,10 +1,23 @@ - /* - * Copyright (C) 2013-2014 Henrik Ekblad - * +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. - * + * + ******************************* + * * DESCRIPTION * The ArduinoGateway prints data received from sensors on the serial link. * The gateway accepts input on seral which will be sent out on radio network. @@ -12,13 +25,14 @@ * The GW code is designed for Arduino Nano 328p / 16MHz * * Wire connections (OPTIONAL): - * - Inclusion button should be connected between digital pin 3 and GND + * - Inclusion button should be connected between digital pin 3 and GND * - RX/TX/ERR leds need to be connected between +5V (anode) and digital pin 6/5/4 with resistor 270-330R in a series * * LEDs (OPTIONAL): * - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved * - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly - * - ERR (red) - fast blink on error during transmission error or recieve crc error + * - ERR (red) - fast blink on error during transmission error or recieve crc error + * */ #define NO_PORTB_PINCHANGES @@ -139,3 +153,4 @@ void serialEvent() { + diff --git a/libraries/MySensors/examples/ServoActuator/ServoActuator.ino b/libraries/MySensors/examples/ServoActuator/ServoActuator.ino index 561fc73..8092412 100644 --- a/libraries/MySensors/examples/ServoActuator/ServoActuator.ino +++ b/libraries/MySensors/examples/ServoActuator/ServoActuator.ino @@ -1,9 +1,35 @@ -// Example showing how to create an atuator for a servo. -// Connect red to +5V, Black or brown to GND and the last cable to Digital pin 3. -// The servo consumes much power and should probably have its own powersource.' -// The arduino might spontanally restart if too much power is used (happend -// to me when servo tried to pass the extreme positions = full load). -// Contribution by: Derek Macias +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * Contribution by: Derek Macias + * + * DESCRIPTION + * Example showing how to create an atuator for a servo. + * Connect red to +5V, Black or brown to GND and the last cable to Digital pin 3. + * The servo consumes much power and should probably have its own powersource.' + * The arduino might spontanally restart if too much power is used (happend + * to me when servo tried to pass the extreme positions = full load). + * http://www.mysensors.org/build/servo + */ #include diff --git a/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino b/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino index 4b7017f..92acedf 100644 --- a/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino +++ b/libraries/MySensors/examples/Sha204Personalizer/Sha204Personalizer.ino @@ -1,24 +1,47 @@ -/* SHA204 personalization sketch - by: Patrick Fallberg - date: January 10, 2015 - - This sketch will write factory default settings to the configuration zone - and then lock it. - It will then either - a. Generate a random value to use as a key which will be stored in - slot 0. The key is printed on UART (115200) in clear text for the user to be - able to use it as a user-supplied key in other personalization executions - where the same key is needed. - b. Use a user-supplied value to use as a key which will be stored in - slot 0. - Finally it will lock the data zone. +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Patrick Fallberg, January 10, 2015 + * + * DESCRIPTION + * SHA204 personalization sketch + * + * This sketch will write factory default settings to the configuration zone + * and then lock it. + * It will then either + * a. Generate a random value to use as a key which will be stored in + * slot 0. The key is printed on UART (115200) in clear text for the user to be + * able to use it as a user-supplied key in other personalization executions + * where the same key is needed. + * b. Use a user-supplied value to use as a key which will be stored in + * slot 0. + * Finally it will lock the data zone. + * + * By default, no locking is performed. User have to manually enable the flags that + * turn on the locking. Furthermore, user have to send a SPACE character on serial + * console when prompted to do any locking. On boards that does not provide UART + * input it is possible to configure the sketch to skip this confirmation. + * Default settings use ATSHA204 on pin 17 (A3). + */ - By default, no locking is performed. User have to manually enable the flags that - turn on the locking. Furthermore, user have to send a SPACE character on serial - console when prompted to do any locking. On boards that does not provide UART - input it is possible to configure the sketch to skip this confirmation. - Default settings use ATSHA204 on pin 17 (A3). -*/ #include #include diff --git a/libraries/MySensors/examples/SoilMoistSensor/SoilMoistSensor.ino b/libraries/MySensors/examples/SoilMoistSensor/SoilMoistSensor.ino index ca6249a..2a2a108 100644 --- a/libraries/MySensors/examples/SoilMoistSensor/SoilMoistSensor.ino +++ b/libraries/MySensors/examples/SoilMoistSensor/SoilMoistSensor.ino @@ -1,3 +1,31 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * Example sketch sending soil moisture alarm to controller + * http://www.mysensors.org/build/moisture + */ + #include #include diff --git a/libraries/MySensors/examples/TimeAwareSensor/TimeAwareSensor.ino b/libraries/MySensors/examples/TimeAwareSensor/TimeAwareSensor.ino index ac3b0b3..7dfe1b0 100644 --- a/libraries/MySensors/examples/TimeAwareSensor/TimeAwareSensor.ino +++ b/libraries/MySensors/examples/TimeAwareSensor/TimeAwareSensor.ino @@ -1,6 +1,30 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * Example sketch showing how to request time from controller. + */ -// Example sketch showing how to request time from controller. -// Created by Henrik Ekblad #include #include diff --git a/libraries/MySensors/examples/TouchDisplaySceneControllerSensor/TouchDisplaySceneControllerSensor.ino b/libraries/MySensors/examples/TouchDisplaySceneControllerSensor/TouchDisplaySceneControllerSensor.ino index 37ebf29..7a1946a 100644 --- a/libraries/MySensors/examples/TouchDisplaySceneControllerSensor/TouchDisplaySceneControllerSensor.ino +++ b/libraries/MySensors/examples/TouchDisplaySceneControllerSensor/TouchDisplaySceneControllerSensor.ino @@ -1,5 +1,28 @@ - -/* +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * http://www.mysensors.org/build/scene_controller * Touch Display Scene Controller build using a touch enabled tft display * attached to a ATMega 2560. This example fetches time from controller and sends * in scene commands to the controller. diff --git a/libraries/MySensors/examples/UVSensor/UVSensor.ino b/libraries/MySensors/examples/UVSensor/UVSensor.ino index 417ae43..a00ed7f 100644 --- a/libraries/MySensors/examples/UVSensor/UVSensor.ino +++ b/libraries/MySensors/examples/UVSensor/UVSensor.ino @@ -1,22 +1,43 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - epierre + * Contribution: bulldoglowell, gizmocuz + * + * DESCRIPTION + * Arduino UVM-30A + * Index table taken from: http://www.elecrow.com/sensors-c-111/environment-c-111_112/uv-sensor-moduleuvm30a-p-716.html + * Because this table is pretty lineair, we can calculate a UVI with one decimal + * + * Connect sensor: + * + * + >>> 5V + * - >>> GND + * out >>> A0 + * + * License: Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) + */ + #include #include -/* - Arduino UVM-30A - - connect the sensor as follows : - - + >>> 5V - - >>> GND - out >>> A0 - - Contribution: epierre, bulldoglowell, gizmocuz - - Index table taken from: http://www.elecrow.com/sensors-c-111/environment-c-111_112/uv-sensor-moduleuvm30a-p-716.html - Because this table is pretty lineair, we can calculate a UVI with one decimal - - License: Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) -*/ - #include #include diff --git a/libraries/MySensors/examples/WaterMeterPulseSensor/WaterMeterPulseSensor.ino b/libraries/MySensors/examples/WaterMeterPulseSensor/WaterMeterPulseSensor.ino index 6e9c4ee..d676d6c 100644 --- a/libraries/MySensors/examples/WaterMeterPulseSensor/WaterMeterPulseSensor.ino +++ b/libraries/MySensors/examples/WaterMeterPulseSensor/WaterMeterPulseSensor.ino @@ -1,13 +1,37 @@ -// -// Use this sensor to measure volume and flow of your house watermeter. -// You need to set the correct pulsefactor of your meter (pulses per m3). -// The sensor starts by fetching current volume reading from gateway (VAR 1). -// Reports both volume and flow back to gateway. -// -// Unfortunately millis() won't increment when the Arduino is in -// sleepmode. So we cannot make this sensor sleep if we also want -// to calculate/report flow. -// +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Henrik Ekblad + * + * DESCRIPTION + * Use this sensor to measure volume and flow of your house watermeter. + * You need to set the correct pulsefactor of your meter (pulses per m3). + * The sensor starts by fetching current volume reading from gateway (VAR 1). + * Reports both volume and flow back to gateway. + * + * Unfortunately millis() won't increment when the Arduino is in + * sleepmode. So we cannot make this sensor sleep if we also want + * to calculate/report flow. + * http://www.mysensors.org/build/pulse_water + */ #include #include From 20c2938d3dc883b17929d50d8ee105f3f27c8e1b Mon Sep 17 00:00:00 2001 From: Tomas Hozza Date: Sun, 12 Apr 2015 19:53:07 +0200 Subject: [PATCH 105/137] Remove the executable bit from source files Signed-off-by: Tomas Hozza --- libraries/MySensors/MyMessage.cpp | 0 libraries/MySensors/MySensor.cpp | 0 libraries/MySensors/utility/RF24.cpp | 0 libraries/MySensors/utility/RF24.h | 0 libraries/MySensors/utility/RF24_config.h | 0 5 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 libraries/MySensors/MyMessage.cpp mode change 100755 => 100644 libraries/MySensors/MySensor.cpp mode change 100755 => 100644 libraries/MySensors/utility/RF24.cpp mode change 100755 => 100644 libraries/MySensors/utility/RF24.h mode change 100755 => 100644 libraries/MySensors/utility/RF24_config.h diff --git a/libraries/MySensors/MyMessage.cpp b/libraries/MySensors/MyMessage.cpp old mode 100755 new mode 100644 diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp old mode 100755 new mode 100644 diff --git a/libraries/MySensors/utility/RF24.cpp b/libraries/MySensors/utility/RF24.cpp old mode 100755 new mode 100644 diff --git a/libraries/MySensors/utility/RF24.h b/libraries/MySensors/utility/RF24.h old mode 100755 new mode 100644 diff --git a/libraries/MySensors/utility/RF24_config.h b/libraries/MySensors/utility/RF24_config.h old mode 100755 new mode 100644 From 192ccf9896316fe51ad98512a2e60df1d7a88036 Mon Sep 17 00:00:00 2001 From: Tomas Hozza Date: Sun, 12 Apr 2015 21:33:48 +0200 Subject: [PATCH 106/137] Fix logging of error if initialization of the radio fails Signed-off-by: Tomas Hozza --- libraries/MySensors/MySensor.cpp | 4 +++- libraries/MySensors/MyTransport.h | 8 +------- libraries/MySensors/MyTransportNRF24.cpp | 6 +++--- libraries/MySensors/MyTransportNRF24.h | 2 +- libraries/MySensors/MyTransportRFM69.cpp | 4 ++-- libraries/MySensors/MyTransportRFM69.h | 2 +- 6 files changed, 11 insertions(+), 15 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 2f98b9e..5e01826 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -101,7 +101,9 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b isGateway = _nodeId == GATEWAY_ADDRESS; // Setup radio - radio.init(); + if (!radio.init()) { + debug(PSTR("radio initialization failed!")); + } #ifdef MY_SIGNING_FEATURE // Read out the signing requirements from EEPROM diff --git a/libraries/MySensors/MyTransport.h b/libraries/MySensors/MyTransport.h index 839dbbd..aab12f3 100644 --- a/libraries/MySensors/MyTransport.h +++ b/libraries/MySensors/MyTransport.h @@ -22,12 +22,6 @@ #include -#ifdef DEBUG -#define debug(x,...) debugPrint(x, ##__VA_ARGS__) -#else -#define debug(x,...) -#endif - #define AUTO 0xFF // 0-254. Id 255 is reserved for auto initialization of nodeId. #define NODE_SENSOR_ID 0xFF // Node child id is always created for when a node @@ -45,7 +39,7 @@ public: // init() // different parameters would be needed depending on radio module (e.g. channel, power, crc, etc.) // keeping these parameters as #define's in MyConfig to streamline the driver interface - virtual void init() = 0; + virtual bool init() = 0; // setAddress(address) // set the node address and start listening to that address (and the broadcast address) virtual void setAddress(uint8_t address) = 0; diff --git a/libraries/MySensors/MyTransportNRF24.cpp b/libraries/MySensors/MyTransportNRF24.cpp index 5635e18..fee7dca 100644 --- a/libraries/MySensors/MyTransportNRF24.cpp +++ b/libraries/MySensors/MyTransportNRF24.cpp @@ -28,13 +28,12 @@ MyTransportNRF24::MyTransportNRF24(uint8_t ce, uint8_t cs, uint8_t paLevel) { } -void MyTransportNRF24::init() { +bool MyTransportNRF24::init() { // Start up the radio library rf24.begin(); if (!rf24.isPVariant()) { - debug(PSTR("check wires\n")); - while(1); + return false; } rf24.setAutoAck(1); rf24.setAutoAck(BROADCAST_PIPE,false); // Turn off auto ack for broadcast @@ -48,6 +47,7 @@ void MyTransportNRF24::init() { // All nodes listen to broadcast pipe (for FIND_PARENT_RESPONSE messages) rf24.openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); + return true; } void MyTransportNRF24::setAddress(uint8_t address) { diff --git a/libraries/MySensors/MyTransportNRF24.h b/libraries/MySensors/MyTransportNRF24.h index 5f9b7b7..8c582fb 100644 --- a/libraries/MySensors/MyTransportNRF24.h +++ b/libraries/MySensors/MyTransportNRF24.h @@ -36,7 +36,7 @@ class MyTransportNRF24 : public MyTransport { public: MyTransportNRF24(uint8_t ce=RF24_CE_PIN, uint8_t cs=RF24_CS_PIN, uint8_t paLevel=RF24_PA_LEVEL); - void init(); + bool init(); void setAddress(uint8_t address); uint8_t getAddress(); bool send(uint8_t to, const void* data, uint8_t len); diff --git a/libraries/MySensors/MyTransportRFM69.cpp b/libraries/MySensors/MyTransportRFM69.cpp index d9b4a9f..4ad8fb4 100644 --- a/libraries/MySensors/MyTransportRFM69.cpp +++ b/libraries/MySensors/MyTransportRFM69.cpp @@ -29,13 +29,13 @@ MyTransportRFM69::MyTransportRFM69(uint8_t freqBand, uint8_t networkId, uint8_t { } -void MyTransportRFM69::init() { +bool MyTransportRFM69::init() { // Start up the radio library (_address will be set later by the MySensors library) radio.initialize(_freqBand, _address, _networkId); #ifdef RFM69_ENABLE_ENCRYPTION radio.encrypt(ENCRYPTKEY); #endif - + return true; } void MyTransportRFM69::setAddress(uint8_t address) { diff --git a/libraries/MySensors/MyTransportRFM69.h b/libraries/MySensors/MyTransportRFM69.h index c564986..afb7643 100644 --- a/libraries/MySensors/MyTransportRFM69.h +++ b/libraries/MySensors/MyTransportRFM69.h @@ -31,7 +31,7 @@ class MyTransportRFM69 : public MyTransport { public: MyTransportRFM69(uint8_t freqBand=RFM69_FREQUENCY, uint8_t networkId=RFM69_NETWORKID, uint8_t slaveSelectPin=RF69_SPI_CS, uint8_t interruptPin=RF69_IRQ_PIN, bool isRFM69HW=false, uint8_t interruptNum=RF69_IRQ_NUM); - void init(); + bool init(); void setAddress(uint8_t address); uint8_t getAddress(); bool send(uint8_t to, const void* data, uint8_t len); From a68350af283985d36bd8693bd5e6f00a616c6a6b Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Sun, 12 Apr 2015 22:03:09 +0200 Subject: [PATCH 107/137] Added a few new sensors --- libraries/MySensors/MyMessage.h | 61 +++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 26 deletions(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index c5b8612..ac9d4de 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -58,8 +58,8 @@ typedef enum { V_WEIGHT, // S_WEIGHT V_DISTANCE, // S_DISTANCE V_IMPEDANCE, // S_MULTIMETER, S_WEIGHT - V_ARMED, // S_DOOR, S_MOTION, S_SMOKE, - V_TRIPPED, // S_DOOR, S_MOTION, S_SMOKE, + V_ARMED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER + V_TRIPPED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER V_WATT, // S_POWER V_KWH, // S_POWER V_SCENE_ON, // S_SCENE_CONTROLLER @@ -88,9 +88,13 @@ typedef enum { V_ID, // S_TEMP // Used for reporting the sensor internal ids (E.g. DS1820b). V_LIGHT_LEVEL_LUX, // S_LIGHT, Light level in lux - V_UNIT_PREFIX // Allows sensors to send in a string representing the - // unit prefix to be displayed in GUI, not parsed! E.g. cm, m, km, inch. - // Can be used for S_DISTANCE + V_UNIT_PREFIX, // Allows sensors to send in a string representing the + // unit prefix to be displayed in GUI, not parsed! E.g. cm, m, km, inch. + // Can be used for S_DISTANCE + V_SOUND_DB, // S_SOUND sound level in db + V_VIBRATION_HZ, // S_VIBRATION vibration i Hz + V_ENCODER_VALUE, // S_ROTARY_ENCODER. Rotary encoder value. + } mysensor_data; // Type of internal messages (for internal messages) @@ -103,35 +107,40 @@ typedef enum { // Type of sensor (for presentation message) typedef enum { - S_DOOR, - S_MOTION, - S_SMOKE, - S_LIGHT, - S_DIMMER, - S_COVER, - S_TEMP, - S_HUM, - S_BARO, - S_WIND, - S_RAIN, - S_UV, - S_WEIGHT, - S_POWER, - S_HEATER, - S_DISTANCE, - S_LIGHT_LEVEL, + S_DOOR, // V_TRIPPED, V_ARMED + S_MOTION, // V_TRIPPED, V_ARMED + S_SMOKE, // V_TRIPPED, V_ARMED + S_LIGHT, // V_LIGHT, V_WATT + S_DIMMER, // V_DIMMER, V_WATT + S_COVER, // V_UP, V_DOWN, V_STOP + S_TEMP, // V_TEMP + S_HUM, // V_HUM + S_BARO, // V_PRESSURE, V_FORECAST + S_WIND, // V_WIND, V_GUST + S_RAIN, // V_RAIN, V_RAINRATE + S_UV, // V_UV + S_WEIGHT, // V_WEIGHT, V_IMPEDANCE + S_POWER, // V_WATT, V_KWH + S_HEATER, // V_HEATER, V_HEATER_SW + S_DISTANCE, // V_DISTANCE + S_LIGHT_LEVEL, // V_LIGHT S_ARDUINO_NODE, S_ARDUINO_REPEATER_NODE, - S_LOCK, - S_IR, - S_WATER, + S_LOCK, // V_LOCK_STATUS + S_IR, // V_IR_SEND, V_IR_RECEIVE + S_WATER, // V_FLOW, V_VOLUME S_AIR_QUALITY, // V_VAR1 S_CUSTOM, S_DUST, // V_DUST_LEVEL S_SCENE_CONTROLLER, // V_SCENE_ON, V_SCENE_OFF. S_RGB_LIGHT, // Send data using V_RGB or V_RGBW S_COLOR_SENSOR, // Send data using V_RGB - S_MULTIMETER // V_VOLTAGE, V_CURRENT, V_IMPEDANCE + S_MULTIMETER, // V_VOLTAGE, V_CURRENT, V_IMPEDANCE + S_SPRINKLER, // V_TRIPPED, V_ARMED + S_WATER_LEAK, // V_TRIPPED, V_ARMED + S_SOUND, // V_TRIPPED, V_ARMED, V_SOUND_DB + S_VIBRATION, // V_TRIPPED, V_ARMED, V_VIBRATION_HZ + S_ROTARY_ENCODER, // V_ENCODER_VALUE } mysensor_sensor; // Type of data stream (for streamed message) From e30dea71ffa1ced9dbcb03480d80e8fc7a661fd7 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Sat, 18 Apr 2015 20:57:15 +0200 Subject: [PATCH 108/137] Fix sleep problem reported by Gary Stofer. --- libraries/MySensors/MyHwATMega328.cpp | 10 +++++++--- libraries/MySensors/MyHwATMega328.h | 1 + libraries/MySensors/MySensor.cpp | 4 ++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/libraries/MySensors/MyHwATMega328.cpp b/libraries/MySensors/MyHwATMega328.cpp index 2281e6c..a9e6de7 100644 --- a/libraries/MySensors/MyHwATMega328.cpp +++ b/libraries/MySensors/MyHwATMega328.cpp @@ -117,7 +117,7 @@ void powerDown(period_t period) { ADCSRA |= (1 << ADEN); } -inline void MyHwATMega328::sleep(unsigned long ms) { +void MyHwATMega328::internalSleep(unsigned long ms) { // Let serial prints finish (debug, log etc) Serial.flush(); pinIntTrigger = 0; @@ -133,13 +133,17 @@ inline void MyHwATMega328::sleep(unsigned long ms) { if (!pinIntTrigger && ms >= 16) { powerDown(SLEEP_15Ms); ms -= 15; } } +void MyHwATMega328::sleep(unsigned long ms) { + internalSleep(ms); +} + bool MyHwATMega328::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { // Let serial prints finish (debug, log etc) bool pinTriggeredWakeup = true; attachInterrupt(interrupt, wakeUp, mode); if (ms>0) { pinIntTrigger = 0; - sleep(ms); + internalSleep(ms); if (0 == pinIntTrigger) { pinTriggeredWakeup = false; } @@ -157,7 +161,7 @@ inline uint8_t MyHwATMega328::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t i attachInterrupt(interrupt2, wakeUp2, mode2); if (ms>0) { pinIntTrigger = 0; - sleep(ms); + internalSleep(ms); if (0 == pinIntTrigger) { retVal = -1; } diff --git a/libraries/MySensors/MyHwATMega328.h b/libraries/MySensors/MyHwATMega328.h index ccb35ba..17a4222 100644 --- a/libraries/MySensors/MyHwATMega328.h +++ b/libraries/MySensors/MyHwATMega328.h @@ -85,5 +85,6 @@ public: void debugPrint(bool isGW, const char *fmt, ... ); #endif private: + void internalSleep(unsigned long ms); }; #endif diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 5e01826..16764b6 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -711,8 +711,8 @@ bool MySensor::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) { return false; } else { #endif - radio.powerDown(); - return hw.sleep(interrupt, mode, ms) ; + radio.powerDown(); + return hw.sleep(interrupt, mode, ms) ; #ifdef MY_OTA_FIRMWARE_FEATURE } #endif From 7bd79f598bdb114b7512b3053278a240d7ee6dbe Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 20 Apr 2015 23:15:41 +0200 Subject: [PATCH 109/137] Do nothing more after radio initialization fails. Thanks @thozza --- libraries/MySensors/MySensor.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 16764b6..837ffd6 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -102,7 +102,8 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b // Setup radio if (!radio.init()) { - debug(PSTR("radio initialization failed!")); + debug(PSTR("radio init fail\n")); + while(1); // Nothing more we can do } #ifdef MY_SIGNING_FEATURE From f015fa1d917adf24798c206ac7b490a3b08ecc02 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 28 Apr 2015 22:28:26 +0200 Subject: [PATCH 110/137] Update MSTimer2 to support ATmega1284P. Thanks Tom. --- libraries/MsTimer2/MsTimer2.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/libraries/MsTimer2/MsTimer2.cpp b/libraries/MsTimer2/MsTimer2.cpp index ead0871..0b0c2dc 100644 --- a/libraries/MsTimer2/MsTimer2.cpp +++ b/libraries/MsTimer2/MsTimer2.cpp @@ -3,6 +3,8 @@ Javier Valencia History: + + 05Apr2015 TRL V0.6a added support for ATmega1284P 29/Dec/11 - V0.6 added support for ATmega32u4, AT90USB646, AT90USB1286 (paul@pjrc.com) some improvements added by Bill Perry note: uses timer4 on Atmega32u4 @@ -49,7 +51,7 @@ void MsTimer2::set(unsigned long ms, void (*f)()) { func = f; -#if defined (__AVR_ATmega168__) || defined (__AVR_ATmega48__) || defined (__AVR_ATmega88__) || defined (__AVR_ATmega328P__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) +#if defined (__AVR_ATmega168__) || defined (__AVR_ATmega48__) || defined (__AVR_ATmega88__) || defined (__AVR_ATmega328P__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) TIMSK2 &= ~(1< Date: Sun, 19 Apr 2015 20:51:48 +0200 Subject: [PATCH 111/137] Add LED blinking support into MySensor without any library dependency Signed-off-by: Tomas Hozza --- libraries/MySensors/MyConfig.h | 20 ++++++++ libraries/MySensors/MySensor.cpp | 86 ++++++++++++++++++++++++++++++++ libraries/MySensors/MySensor.h | 29 +++++++++++ 3 files changed, 135 insertions(+) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 437ef3e..c2148ab 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -45,6 +45,26 @@ #define MY_OTA_FLASH_JDECID 0x1F65 +/********************************** +* Information LEDs blinking +***********************************/ +// This feature enables LEDs blinking on message receive, transmit +// or if some error occured. This was commonly used only in gateways, +// but now can be used in any sensor node. Also the LEDs can now be +// disabled in the gateway. + +// #define WITH_LEDS_BLINKING + +// default LEDs blinking period in milliseconds +#define DEFAULT_LED_BLINK_PERIOD 300 +// The RX LED default pin +#define DEFAULT_RX_LED_PIN 8 +// The TX LED default pin +#define DEFAULT_TX_LED_PIN 9 +// The Error LED default pin +#define DEFAULT_ERR_LED_PIN 7 + + /********************************** * Message Signing Settings ***********************************/ diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 837ffd6..f059b9e 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -52,6 +52,9 @@ static inline bool isValidDistance( const uint8_t distance ) { MySensor::MySensor(MyTransport &_radio, MyHw &_hw #ifdef MY_SIGNING_FEATURE , MySigning &_signer +#endif +#ifdef WITH_LEDS_BLINKING + , uint8_t _rx, uint8_t _tx, uint8_t _er, unsigned long _blink_period #endif ) : @@ -59,6 +62,9 @@ MySensor::MySensor(MyTransport &_radio, MyHw &_hw #ifdef MY_SIGNING_FEATURE signer(_signer), #endif +#ifdef WITH_LEDS_BLINKING + pinRx(_rx), pinTx(_tx), pinEr(_er), ledBlinkPeriod(_blink_period), +#endif #ifdef MY_OTA_FIRMWARE_FEATURE flash(MY_OTA_FLASH_SS, MY_OTA_FLASH_JDECID), #endif @@ -90,6 +96,64 @@ bool MySensor::isValidFirmware() { #endif +#ifdef WITH_LEDS_BLINKING +void MySensor::handleLedsBlinking() { + static unsigned long next_time = hw_millis() + ledBlinkPeriod; + + // Just return if it is not the time... + // http://playground.arduino.cc/Code/TimingRollover + if ((long)(hw_millis() - next_time) < 0) + return; + else + next_time = hw_millis() + ledBlinkPeriod; + + // do the actual blinking + if(countRx && countRx != 255) { + // switch led on + digitalWrite(pinRx, LOW); + } + else if(!countRx) { + // switching off + digitalWrite(pinRx, HIGH); + } + if(countRx != 255) + --countRx; + + if(countTx && countTx != 255) { + // switch led on + digitalWrite(pinTx, LOW); + } + else if(!countTx) { + // switching off + digitalWrite(pinTx, HIGH); + } + if(countTx != 255) + --countTx; + + if(countErr && countErr != 255) { + // switch led on + digitalWrite(pinEr, LOW); + } + else if(!countErr) { + // switching off + digitalWrite(pinEr, HIGH); + } + if(countErr != 255) + --countErr; +} + +void MySensor::rxBlink(uint8_t cnt) { + if(countRx == 255) { countRx = cnt; } +} + +void MySensor::txBlink(uint8_t cnt) { + if(countTx == 255) { countTx = cnt; } +} + +void MySensor::errBlink(uint8_t cnt) { + if(countErr == 255) { countErr = cnt; } +} +#endif void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId) { hw_init(); @@ -111,6 +175,23 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b hw_readConfigBlock((void*)doSign, (void*)EEPROM_SIGNING_REQUIREMENT_TABLE_ADDRESS, sizeof(doSign)); #endif +#ifdef WITH_LEDS_BLINKING + // Setup led pins + pinMode(pinRx, OUTPUT); + pinMode(pinTx, OUTPUT); + pinMode(pinEr, OUTPUT); + + // Set initial state of leds + digitalWrite(pinRx, HIGH); + digitalWrite(pinTx, HIGH); + digitalWrite(pinEr, HIGH); + + // initialize counters + countRx = 0; + countTx = 0; + countErr = 0; +#endif + if (isGateway) { // Set configuration for gateway nc.parentNodeId = GATEWAY_ADDRESS; @@ -408,6 +489,11 @@ void MySensor::requestTime(void (* _timeCallback)(unsigned long)) { boolean MySensor::process() { hw_watchdogReset(); + +#ifdef WITH_LEDS_BLINKING + handleLedsBlinking(); +#endif + uint8_t to = 0; if (!radio.available(&to)) { diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 0081b90..9917b66 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -145,6 +145,12 @@ class MySensor MySensor(MyTransport &radio =*new MyTransportNRF24(), MyHw &hw=*new MyHwDriver() #ifdef MY_SIGNING_FEATURE , MySigning &signer=*new MySigningNone() +#endif +#ifdef WITH_LEDS_BLINKING + , uint8_t _rx=DEFAULT_RX_LED_PIN, + uint8_t _tx=DEFAULT_TX_LED_PIN, + uint8_t _er=DEFAULT_ERR_LED_PIN, + unsigned long _blink_period=DEFAULT_LED_BLINK_PERIOD #endif ); @@ -299,6 +305,15 @@ class MySensor */ int8_t sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms=0); +#ifdef WITH_LEDS_BLINKING + /** + * Blink with LEDs + * @param cnt how many blink cycles to keep the LED on. Default cycle is 300ms + */ + void rxBlink(uint8_t cnt); + void txBlink(uint8_t cnt); + void errBlink(uint8_t cnt); +#endif protected: NodeConfig nc; // Essential settings for node to work @@ -324,6 +339,20 @@ class MySensor MySigning& signer; #endif +#ifdef WITH_LEDS_BLINKING + uint8_t pinRx; // Rx led pin + uint8_t pinTx; // Tx led pin + uint8_t pinEr; // Err led pin + + // these variables don't need to be volatile, since we are not using interrupts + uint8_t countRx; + uint8_t countTx; + uint8_t countErr; + + unsigned long ledBlinkPeriod; + void handleLedsBlinking(); // do the actual blinking +#endif + MyTransport& radio; MyHw& hw; From 24464a6255988819d8ed4f87b1163d25d9ff1495 Mon Sep 17 00:00:00 2001 From: Tomas Hozza Date: Sun, 19 Apr 2015 21:07:03 +0200 Subject: [PATCH 112/137] Use LED blinking in MySensor where appropriate Signed-off-by: Tomas Hozza --- libraries/MySensors/MySensor.cpp | 33 ++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index f059b9e..cb0e026 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -327,12 +327,18 @@ boolean MySensor::sendRoute(MyMessage &message) { // If we still don't have any parent id, re-request and skip this message. if (nc.parentNodeId == AUTO) { findParentNode(); +#ifdef WITH_LEDS_BLINKING + errBlink(1); +#endif return false; } // If we still don't have any node id, re-request and skip this message. if (nc.nodeId == AUTO) { requestNodeId(); +#ifdef WITH_LEDS_BLINKING + errBlink(1); +#endif return false; } @@ -369,10 +375,16 @@ boolean MySensor::sendRoute(MyMessage &message) { } if (hw_millis() - enter > MY_VERIFICATION_TIMEOUT_MS) { debug(PSTR("nonce tmo\n")); +#ifdef WITH_LEDS_BLINKING + errBlink(1); +#endif return false; } if (!signOk) { debug(PSTR("sign fail\n")); +#ifdef WITH_LEDS_BLINKING + errBlink(1); +#endif return false; } // After this point, only the 'last' member of the message structure is allowed to be altered if the message has been signed, @@ -431,6 +443,9 @@ boolean MySensor::sendRoute(MyMessage &message) { if (!ok) { // Failure when sending to parent node. The parent node might be down and we // need to find another route to gateway. +#ifdef WITH_LEDS_BLINKING + errBlink(1); +#endif failedTransmissions++; if (autoFindParent && failedTransmissions > SEARCH_FAILURES) { findParentNode(); @@ -445,6 +460,9 @@ boolean MySensor::sendWrite(uint8_t to, MyMessage &message) { mSetVersion(message, PROTOCOL_VERSION); uint8_t length = mGetSigned(message) ? MAX_MESSAGE_LENGTH : mGetLength(message); message.last = nc.nodeId; +#ifdef WITH_LEDS_BLINKING + txBlink(1); +#endif bool ok = radio.send(to, &message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length)); debug(PSTR("send: %d-%d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d,sg=%d,st=%s:%s\n"), @@ -504,6 +522,9 @@ boolean MySensor::process() { debug(PSTR("fw upd fail\n")); // Give up. We have requested MY_OTA_RETRY times without any packet in return. fwUpdateOngoing = false; +#ifdef WITH_LEDS_BLINKING + errBlink(1); +#endif return false; } fwRetry--; @@ -525,6 +546,9 @@ boolean MySensor::process() { #endif uint8_t len = radio.receive((uint8_t *)&msg); +#ifdef WITH_LEDS_BLINKING + rxBlink(1); +#endif #ifdef MY_SIGNING_FEATURE // Before processing message, reject unsigned messages if signing is required and check signature (if it is signed and addressed to us) @@ -537,10 +561,16 @@ boolean MySensor::process() { if (!mGetSigned(msg)) { // Got unsigned message that should have been signed debug(PSTR("no sign\n")); +#ifdef WITH_LEDS_BLINKING + errBlink(1); +#endif return false; } else if (!signer.verifyMsg(msg)) { debug(PSTR("verify fail\n")); +#ifdef WITH_LEDS_BLINKING + errBlink(1); +#endif return false; // This signed message has been tampered with! } } @@ -554,6 +584,9 @@ boolean MySensor::process() { if(!(mGetVersion(msg) == PROTOCOL_VERSION)) { debug(PSTR("ver mismatch\n")); +#ifdef WITH_LEDS_BLINKING + errBlink(1); +#endif return false; } From 0d6da230c5236daacb6375b6d04b30a3e91b90dc Mon Sep 17 00:00:00 2001 From: Tomas Hozza Date: Wed, 6 May 2015 21:30:49 +0200 Subject: [PATCH 113/137] SerialGateway: Use internal LEDs feature for blinking Signed-off-by: Tomas Hozza --- .../examples/SerialGateway/GatewayUtil.h | 97 +++---------------- .../examples/SerialGateway/SerialGateway.ino | 15 +-- 2 files changed, 21 insertions(+), 91 deletions(-) diff --git a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h index 532d9ca..bf24038 100644 --- a/libraries/MySensors/examples/SerialGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/SerialGateway/GatewayUtil.h @@ -27,9 +27,6 @@ #ifdef ARDUINO -uint8_t pinRx = 8; // Rx led pin -uint8_t pinTx = 9; // Tx led pin -uint8_t pinEr = 7; // Err led pin uint8_t inclusionTime = 1; // Number of minutes inclusion mode is enabled uint8_t pinInclusion = 3; // Input pin that should trigger inclusion mode @@ -37,56 +34,28 @@ uint8_t pinInclusion = 3; // Input pin that should trigger inclusion mode #define MAX_SEND_LENGTH 120 // Max buffersize needed for messages destined for controller volatile boolean buttonTriggeredInclusion; -volatile uint8_t countRx; -volatile uint8_t countTx; -volatile uint8_t countErr; boolean inclusionMode; // Keeps track on inclusion mode void (*serial)(const char *fmt, ... ); MyParserSerial parser; void setInclusionMode(boolean newMode); -void txBlink(uint8_t cnt); -void rxBlink(uint8_t cnt); -void errBlink(uint8_t cnt); char convBuf[MAX_PAYLOAD*2+1]; char serialBuffer[MAX_SEND_LENGTH]; // Buffer for building string when sending data to vera unsigned long inclusionStartTime; -void setupGateway(uint8_t _rx, uint8_t _tx, uint8_t _er, uint8_t _inc, uint8_t _incTime, void (* _serial)(const char *, ... )) { +void setupGateway(uint8_t _inc, uint8_t _incTime, void (* _serial)(const char *, ... )) { inclusionMode = 0; buttonTriggeredInclusion = false; serial = _serial; - pinRx = _rx; - pinTx = _tx; - pinEr = _er; pinInclusion = _inc; inclusionTime = _incTime; - countRx = 0; - countTx = 0; - countErr = 0; - - - // Setup led pins - pinMode(pinRx, OUTPUT); - pinMode(pinTx, OUTPUT); - pinMode(pinEr, OUTPUT); - digitalWrite(pinRx, LOW); - digitalWrite(pinTx, LOW); - digitalWrite(pinEr, LOW); - // Setup digital in that triggers inclusion mode pinMode(pinInclusion, INPUT); digitalWrite(pinInclusion, HIGH); - - // Set initial state of leds - digitalWrite(pinRx, HIGH); - digitalWrite(pinTx, HIGH); - digitalWrite(pinEr, HIGH); - } @@ -96,11 +65,11 @@ void startInclusionInterrupt() { } void incomingMessage(const MyMessage &message) { - if (mGetCommand(message) == C_PRESENTATION && inclusionMode) { - rxBlink(3); - } else { - rxBlink(1); - } +// if (mGetCommand(message) == C_PRESENTATION && inclusionMode) { +// gw.rxBlink(3); +// } else { +// gw.rxBlink(1); +// } // Pass along the message from sensors to serial line serial(PSTR("%d;%d;%d;%d;%d;%s\n"),message.sender, message.sensor, mGetCommand(message), mGetAck(message), message.type, message.getString(convBuf)); } @@ -126,7 +95,7 @@ void checkInclusionFinished() { } } -void parseAndSend(MySensor gw, char *commandBuffer) { +void parseAndSend(MySensor &gw, char *commandBuffer) { boolean ok; MyMessage &msg = gw.getLastMessage(); @@ -143,10 +112,14 @@ void parseAndSend(MySensor gw, char *commandBuffer) { setInclusionMode(atoi(msg.data) == 1); } } else { - txBlink(1); + #ifdef WITH_LEDS_BLINKING + gw.txBlink(1); + #endif ok = gw.sendRoute(msg); if (!ok) { - errBlink(1); + #ifdef WITH_LEDS_BLINKING + gw.errBlink(1); + #endif } } } @@ -165,50 +138,6 @@ void setInclusionMode(boolean newMode) { } - - -void ledTimersInterrupt() { - if(countRx && countRx != 255) { - // switch led on - digitalWrite(pinRx, LOW); - } else if(!countRx) { - // switching off - digitalWrite(pinRx, HIGH); - } - if(countRx != 255) { countRx--; } - - if(countTx && countTx != 255) { - // switch led on - digitalWrite(pinTx, LOW); - } else if(!countTx) { - // switching off - digitalWrite(pinTx, HIGH); - } - if(countTx != 255) { countTx--; } - else if(inclusionMode) { countTx = 8; } - - if(countErr && countErr != 255) { - // switch led on - digitalWrite(pinEr, LOW); - } else if(!countErr) { - // switching off - digitalWrite(pinEr, HIGH); - } - if(countErr != 255) { countErr--; } -} - -void rxBlink(uint8_t cnt) { - if(countRx == 255) { countRx = cnt; } -} -void txBlink(uint8_t cnt) { - if(countTx == 255 && !inclusionMode) { countTx = cnt; } -} -void errBlink(uint8_t cnt) { - if(countErr == 255) { countErr = cnt; } -} - - - #else #error This example is only for use on Arduino. #endif // ARDUINO diff --git a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino index 9bfa910..7478665 100644 --- a/libraries/MySensors/examples/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -29,6 +29,7 @@ * - RX/TX/ERR leds need to be connected between +5V (anode) and digital pin 6/5/4 with resistor 270-330R in a series * * LEDs (OPTIONAL): + * - To use the feature, uncomment WITH_LEDS_BLINKING in MyConfig.h * - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved * - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly * - ERR (red) - fast blink on error during transmission error or recieve crc error @@ -48,7 +49,6 @@ #include #include #include -#include #include #include "GatewayUtil.h" @@ -59,7 +59,7 @@ #define RADIO_TX_LED_PIN 5 // the PCB, on board LED // NRFRF24L01 radio driver (set low transmit power by default) -MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); //MyTransportRFM69 transport; // Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) @@ -71,7 +71,12 @@ MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); MyHwATMega328 hw; // Construct MySensors library (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) +// To use LEDs blinking, uncomment WITH_LEDS_BLINKING in MyConfig.h +#ifdef WITH_LEDS_BLINKING +MySensor gw(transport, hw /*, signer*/, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN); +#else MySensor gw(transport, hw /*, signer*/); +#endif char inputString[MAX_RECEIVE_LENGTH] = ""; // A string to hold incoming commands from serial/ethernet interface int inputPos = 0; @@ -92,11 +97,7 @@ void setup() { gw.begin(incomingMessage, 0, true, 0); - setupGateway(RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN, INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output); - - // Add led timer interrupt - MsTimer2::set(300, ledTimersInterrupt); - MsTimer2::start(); + setupGateway(INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output); // Add interrupt for inclusion button to pin PCintPort::attachInterrupt(pinInclusion, startInclusionInterrupt, RISING); From 29b86801fbffa7853ea68eeba8a86a31c0f8f81f Mon Sep 17 00:00:00 2001 From: Tomas Hozza Date: Wed, 6 May 2015 21:41:54 +0200 Subject: [PATCH 114/137] EthernetGateway: Use internal LEDs feature for blinking Signed-off-by: Tomas Hozza --- .../EthernetGateway/EthernetGateway.ino | 12 ++- .../examples/EthernetGateway/GatewayUtil.h | 97 +++---------------- 2 files changed, 20 insertions(+), 89 deletions(-) diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 562b28d..383cbdf 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -46,6 +46,7 @@ * E.g. If you want to use the defualt values in this sketch enter: 192.168.178.66:5003 * * LED purposes: + * - To use the feature, uncomment WITH_LEDS_BLINKING in MyConfig.h * - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved * - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly * - ERR (red) - fast blink on error during transmission error or recieve crc error @@ -68,7 +69,6 @@ #include #include #include -#include #include #include "GatewayUtil.h" @@ -104,7 +104,12 @@ MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); MyHwATMega328 hw; // Construct MySensors library (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) +// To use LEDs blinking, uncomment WITH_LEDS_BLINKING in MyConfig.h +#ifdef WITH_LEDS_BLINKING +MySensor gw(transport, hw /*, signer*/, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN); +#else MySensor gw(transport, hw /*, signer*/); +#endif #define IP_PORT 5003 // The port you want to open @@ -136,11 +141,8 @@ void output(const char *fmt, ... ) { void setup() { Ethernet.begin(mac, myIp); - setupGateway(RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN, INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output); - // Add led timer interrupt - MsTimer2::set(300, ledTimersInterrupt); - MsTimer2::start(); + setupGateway(INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output); // Add interrupt for inclusion button to pin PCintPort::attachInterrupt(pinInclusion, startInclusionInterrupt, RISING); diff --git a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h index 2c1b22c..64730f2 100644 --- a/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h +++ b/libraries/MySensors/examples/EthernetGateway/GatewayUtil.h @@ -7,9 +7,6 @@ #ifdef ARDUINO -uint8_t pinRx = 8; // Rx led pin -uint8_t pinTx = 9; // Tx led pin -uint8_t pinEr = 7; // Err led pin uint8_t inclusionTime = 1; // Number of minutes inclusion mode is enabled uint8_t pinInclusion = 3; // Input pin that should trigger inclusion mode @@ -17,56 +14,28 @@ uint8_t pinInclusion = 3; // Input pin that should trigger inclusion mode #define MAX_SEND_LENGTH 120 // Max buffersize needed for messages destined for controller volatile boolean buttonTriggeredInclusion; -volatile uint8_t countRx; -volatile uint8_t countTx; -volatile uint8_t countErr; boolean inclusionMode; // Keeps track on inclusion mode void (*serial)(const char *fmt, ... ); MyParserSerial parser; void setInclusionMode(boolean newMode); -void txBlink(uint8_t cnt); -void rxBlink(uint8_t cnt); -void errBlink(uint8_t cnt); char convBuf[MAX_PAYLOAD*2+1]; char serialBuffer[MAX_SEND_LENGTH]; // Buffer for building string when sending data to vera unsigned long inclusionStartTime; -void setupGateway(uint8_t _rx, uint8_t _tx, uint8_t _er, uint8_t _inc, uint8_t _incTime, void (* _serial)(const char *, ... )) { +void setupGateway(uint8_t _inc, uint8_t _incTime, void (* _serial)(const char *, ... )) { inclusionMode = 0; buttonTriggeredInclusion = false; serial = _serial; - pinRx = _rx; - pinTx = _tx; - pinEr = _er; pinInclusion = _inc; inclusionTime = _incTime; - countRx = 0; - countTx = 0; - countErr = 0; - - - // Setup led pins - pinMode(pinRx, OUTPUT); - pinMode(pinTx, OUTPUT); - pinMode(pinEr, OUTPUT); - digitalWrite(pinRx, LOW); - digitalWrite(pinTx, LOW); - digitalWrite(pinEr, LOW); - // Setup digital in that triggers inclusion mode pinMode(pinInclusion, INPUT); digitalWrite(pinInclusion, HIGH); - - // Set initial state of leds - digitalWrite(pinRx, HIGH); - digitalWrite(pinTx, HIGH); - digitalWrite(pinEr, HIGH); - } @@ -76,11 +45,11 @@ void startInclusionInterrupt() { } void incomingMessage(const MyMessage &message) { - if (mGetCommand(message) == C_PRESENTATION && inclusionMode) { - rxBlink(3); - } else { - rxBlink(1); - } +// if (mGetCommand(message) == C_PRESENTATION && inclusionMode) { +// gw.rxBlink(3); +// } else { +// gw.rxBlink(1); +// } // Pass along the message from sensors to serial line serial(PSTR("%d;%d;%d;%d;%d;%s\n"),message.sender, message.sensor, mGetCommand(message), mGetAck(message), message.type, message.getString(convBuf)); } @@ -106,7 +75,7 @@ void checkInclusionFinished() { } } -void parseAndSend(MySensor gw, char *commandBuffer) { +void parseAndSend(MySensor &gw, char *commandBuffer) { boolean ok; MyMessage &msg = gw.getLastMessage(); @@ -123,10 +92,14 @@ void parseAndSend(MySensor gw, char *commandBuffer) { setInclusionMode(atoi(msg.data) == 1); } } else { - txBlink(1); + #ifdef WITH_LEDS_BLINKING + gw.txBlink(1); + #endif ok = gw.sendRoute(msg); if (!ok) { - errBlink(1); + #ifdef WITH_LEDS_BLINKING + gw.errBlink(1); + #endif } } } @@ -145,50 +118,6 @@ void setInclusionMode(boolean newMode) { } - - -void ledTimersInterrupt() { - if(countRx && countRx != 255) { - // switch led on - digitalWrite(pinRx, LOW); - } else if(!countRx) { - // switching off - digitalWrite(pinRx, HIGH); - } - if(countRx != 255) { countRx--; } - - if(countTx && countTx != 255) { - // switch led on - digitalWrite(pinTx, LOW); - } else if(!countTx) { - // switching off - digitalWrite(pinTx, HIGH); - } - if(countTx != 255) { countTx--; } - else if(inclusionMode) { countTx = 8; } - - if(countErr && countErr != 255) { - // switch led on - digitalWrite(pinEr, LOW); - } else if(!countErr) { - // switching off - digitalWrite(pinEr, HIGH); - } - if(countErr != 255) { countErr--; } -} - -void rxBlink(uint8_t cnt) { - if(countRx == 255) { countRx = cnt; } -} -void txBlink(uint8_t cnt) { - if(countTx == 255 && !inclusionMode) { countTx = cnt; } -} -void errBlink(uint8_t cnt) { - if(countErr == 255) { countErr = cnt; } -} - - - #else #error This example is only for use on Arduino. #endif // ARDUINO From 387aaba46e255f033b76d5fe4bc39a9866871e4f Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 8 Jun 2015 21:58:40 +0200 Subject: [PATCH 115/137] Fix error in V/S comments --- libraries/MySensors/MyMessage.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index ac9d4de..471bf49 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -45,7 +45,7 @@ typedef enum { typedef enum { V_TEMP, // S_TEMP V_HUM, // S_HUM - V_LIGHT, // S_LIGHT (Light level in uncalibrated percentage) + V_LIGHT, // S_LIGHT, S_DIMMER V_DIMMER, // S_DIMMER V_PRESSURE, // S_BARO V_FORECAST, // S_BARO @@ -60,13 +60,13 @@ typedef enum { V_IMPEDANCE, // S_MULTIMETER, S_WEIGHT V_ARMED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER V_TRIPPED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER - V_WATT, // S_POWER + V_WATT, // S_POWER, S_LIGHT, S_DIMMER V_KWH, // S_POWER V_SCENE_ON, // S_SCENE_CONTROLLER V_SCENE_OFF, // S_SCENE_CONTROLLER V_HEATER, // S_HEATER V_HEATER_SW, // S_HEATER - V_LIGHT_LEVEL, // S_LIGHT_LEVEL + V_LIGHT_LEVEL, // S_LIGHT_LEVEL (light level in uncalibrated percentage) V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, V_UP, // S_COVER V_DOWN, // S_COVER @@ -111,7 +111,7 @@ typedef enum { S_MOTION, // V_TRIPPED, V_ARMED S_SMOKE, // V_TRIPPED, V_ARMED S_LIGHT, // V_LIGHT, V_WATT - S_DIMMER, // V_DIMMER, V_WATT + S_DIMMER, // V_LIGHT, V_DIMMER, V_WATT S_COVER, // V_UP, V_DOWN, V_STOP S_TEMP, // V_TEMP S_HUM, // V_HUM @@ -123,7 +123,7 @@ typedef enum { S_POWER, // V_WATT, V_KWH S_HEATER, // V_HEATER, V_HEATER_SW S_DISTANCE, // V_DISTANCE - S_LIGHT_LEVEL, // V_LIGHT + S_LIGHT_LEVEL, // V_LIGHT_LEVEL S_ARDUINO_NODE, S_ARDUINO_REPEATER_NODE, S_LOCK, // V_LOCK_STATUS From f642ec8bf6bea4545cf181bfba53236da888d212 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 9 Jun 2015 23:05:45 +0200 Subject: [PATCH 116/137] Added optional description when presenting sensors. --- libraries/MySensors/MySensor.cpp | 4 ++-- libraries/MySensors/MySensor.h | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index cb0e026..184317a 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -483,8 +483,8 @@ void MySensor::sendBatteryLevel(uint8_t value, bool enableAck) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_BATTERY_LEVEL, enableAck).set(value)); } -void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck) { - sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(LIBRARY_VERSION)); +void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck, const char*description) { + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(description)); } void MySensor::sendSketchInfo(const char *name, const char *version, bool enableAck) { diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 9917b66..5798ac7 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -178,8 +178,9 @@ class MySensor * @param sensorId Select a unique sensor id for this sensor. Choose a number between 0-254. * @param sensorType The sensor type. See sensor typedef in MyMessage.h. * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. + * @param description A textual description of the sensor. Defaults to library version. */ - void present(uint8_t sensorId, uint8_t sensorType, bool ack=false); + void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=LIBRARY_VERSION); /** * Sends sketch meta information to the gateway. Not mandatory but a nice thing to do. From e111d64c3186a2691d8e66d72f7f715c09c8544e Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 9 Jun 2015 23:47:44 +0200 Subject: [PATCH 117/137] Fix: Default to empty sensor description --- libraries/MySensors/MySensor.cpp | 2 +- libraries/MySensors/MySensor.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 184317a..b953fd7 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -484,7 +484,7 @@ void MySensor::sendBatteryLevel(uint8_t value, bool enableAck) { } void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck, const char*description) { - sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(description)); + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(childSensorId==NODE_SENSOR_ID?LIBRARY_VERSION:description)); } void MySensor::sendSketchInfo(const char *name, const char *version, bool enableAck) { diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 5798ac7..0c89604 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -180,7 +180,7 @@ class MySensor * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. * @param description A textual description of the sensor. Defaults to library version. */ - void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=LIBRARY_VERSION); + void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=""); /** * Sends sketch meta information to the gateway. Not mandatory but a nice thing to do. From 52916cb8fe3b0bdddca63f37346bcca1acb214bd Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 9 Jun 2015 23:58:16 +0200 Subject: [PATCH 118/137] Fix comment for presentation --- libraries/MySensors/MySensor.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 0c89604..1cda7d1 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -178,7 +178,7 @@ class MySensor * @param sensorId Select a unique sensor id for this sensor. Choose a number between 0-254. * @param sensorType The sensor type. See sensor typedef in MyMessage.h. * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. - * @param description A textual description of the sensor. Defaults to library version. + * @param description A textual description of the sensor. */ void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=""); From 51d22c6936707e5f594786c473da0b32789f8bcc Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 10 Jun 2015 23:56:40 +0200 Subject: [PATCH 119/137] Change argument order in presentation --- libraries/MySensors/MySensor.cpp | 2 +- libraries/MySensors/MySensor.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index b953fd7..010cd19 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -483,7 +483,7 @@ void MySensor::sendBatteryLevel(uint8_t value, bool enableAck) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_BATTERY_LEVEL, enableAck).set(value)); } -void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck, const char*description) { +void MySensor::present(uint8_t childSensorId, uint8_t sensorType, const char*description, bool enableAck) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(childSensorId==NODE_SENSOR_ID?LIBRARY_VERSION:description)); } diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 1cda7d1..8842a6f 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -177,10 +177,10 @@ class MySensor * * @param sensorId Select a unique sensor id for this sensor. Choose a number between 0-254. * @param sensorType The sensor type. See sensor typedef in MyMessage.h. - * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. * @param description A textual description of the sensor. + * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. */ - void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=""); + void present(uint8_t sensorId, uint8_t sensorType, const char *description="", bool ack=false); /** * Sends sketch meta information to the gateway. Not mandatory but a nice thing to do. From 938ade88232b12e364368e6004e2cf4d31008154 Mon Sep 17 00:00:00 2001 From: Kolbi Date: Wed, 17 Jun 2015 14:33:37 +0200 Subject: [PATCH 120/137] Update DallasTemperatureSensor.ino Small code improvements --- .../DallasTemperatureSensor.ino | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino index 5ac41b4..0c2878b 100644 --- a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino @@ -32,8 +32,8 @@ #define ONE_WIRE_BUS 3 // Pin where dallase sensor is connected #define MAX_ATTACHED_DS18B20 16 unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) -OneWire oneWire(ONE_WIRE_BUS); -DallasTemperature sensors(&oneWire); +OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) +DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature. MySensor gw; float lastTemperature[MAX_ATTACHED_DS18B20]; int numSensors=0; @@ -44,8 +44,8 @@ MyMessage msg(0,V_TEMP); void setup() { - // Startup OneWire - sensors.begin(); + // Startup up the OneWire library + sensors.begin(); // Startup and initialize MySensors library. Set callback for incoming messages. gw.begin(); @@ -78,10 +78,11 @@ void loop() float temperature = static_cast(static_cast((gw.getConfig().isMetric?sensors.getTempCByIndex(i):sensors.getTempFByIndex(i)) * 10.)) / 10.; // Only send data if temperature has changed and no error - if (lastTemperature[i] != temperature && temperature != -127.00) { + if (lastTemperature[i] != temperature && temperature != -127.00 && temperature != 85.00) { // Send in the new temperature gw.send(msg.setSensor(i).set(temperature,1)); + // Save new temperatures for next compare lastTemperature[i]=temperature; } } From 8d7d63dfd9322a91bdf743fef6aeff39f78933cc Mon Sep 17 00:00:00 2001 From: Kolbi Date: Wed, 17 Jun 2015 14:34:43 +0200 Subject: [PATCH 121/137] Update DallasTemperatureSensor.ino --- .../DallasTemperatureSensor/DallasTemperatureSensor.ino | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino index 0c2878b..05da63e 100644 --- a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino @@ -33,7 +33,7 @@ #define MAX_ATTACHED_DS18B20 16 unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) -DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature. +DallasTemperature sensors(&oneWire); // Pass the oneWire reference to Dallas Temperature. MySensor gw; float lastTemperature[MAX_ATTACHED_DS18B20]; int numSensors=0; @@ -45,10 +45,10 @@ MyMessage msg(0,V_TEMP); void setup() { // Startup up the OneWire library - sensors.begin(); + sensors.begin(); // Startup and initialize MySensors library. Set callback for incoming messages. - gw.begin(); + gw.begin(); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Temperature Sensor", "1.0"); From d90e2d9aac642604f89960845fd4fbca744de72b Mon Sep 17 00:00:00 2001 From: Kolbi Date: Wed, 17 Jun 2015 14:59:37 +0200 Subject: [PATCH 122/137] Update DallasTemperatureSensor.ino Updated version number to 1.1 since minor changes... --- .../DallasTemperatureSensor/DallasTemperatureSensor.ino | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino index 05da63e..dd74739 100644 --- a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino @@ -29,6 +29,8 @@ #include #include +#define COMPARE_TEMP 1 // Send temperature only if changed? 1 = Yes 0 = No + #define ONE_WIRE_BUS 3 // Pin where dallase sensor is connected #define MAX_ATTACHED_DS18B20 16 unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) @@ -51,7 +53,7 @@ void setup() gw.begin(); // Send the sketch version information to the gateway and Controller - gw.sendSketchInfo("Temperature Sensor", "1.0"); + gw.sendSketchInfo("Temperature Sensor", "1.1"); // Fetch the number of attached temperature sensors numSensors = sensors.getDeviceCount(); @@ -78,7 +80,11 @@ void loop() float temperature = static_cast(static_cast((gw.getConfig().isMetric?sensors.getTempCByIndex(i):sensors.getTempFByIndex(i)) * 10.)) / 10.; // Only send data if temperature has changed and no error + #if COMPARE_TEMP == 1 if (lastTemperature[i] != temperature && temperature != -127.00 && temperature != 85.00) { + #else + if (temperature != -127.00 && temperature != 85.00) { + #endif // Send in the new temperature gw.send(msg.setSensor(i).set(temperature,1)); From ed939e7efd3be3bfad8ac72778da844f5962a165 Mon Sep 17 00:00:00 2001 From: Kolbi Date: Wed, 17 Jun 2015 15:42:50 +0200 Subject: [PATCH 123/137] Update BatteryPoweredSensor.ino Made debugging informations (Serial Print) optionally through setting --- .../examples/BatteryPoweredSensor/BatteryPoweredSensor.ino | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino b/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino index 7dbd93b..40c51da 100644 --- a/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino +++ b/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino @@ -30,6 +30,8 @@ #include #include +#define DEBUG 1 // Debug enables Serial.print 1 = Yes 0 = No + int BATTERY_SENSE_PIN = A0; // select the input pin for the battery sense point MySensor gw; @@ -50,7 +52,9 @@ void loop() { // get the battery Voltage int sensorValue = analogRead(BATTERY_SENSE_PIN); + #if DEBUG > 0 Serial.println(sensorValue); + #endif // 1M, 470K divider across battery and using internal ADC ref of 1.1V // Sense point is bypassed with 0.1 uF cap to reduce noise at that point @@ -59,6 +63,7 @@ void loop() float batteryV = sensorValue * 0.003363075; int batteryPcnt = sensorValue / 10; + #if DEBUG > 0 Serial.print("Battery Voltage: "); Serial.print(batteryV); Serial.println(" V"); @@ -66,6 +71,7 @@ void loop() Serial.print("Battery percent: "); Serial.print(batteryPcnt); Serial.println(" %"); + #endif if (oldBatteryPcnt != batteryPcnt) { // Power up radio after sleep From 1049246a88bf91484ed44f0be878c2fa379d0600 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 20 Jun 2015 13:39:30 +0200 Subject: [PATCH 124/137] Make sure SPI backend is initialized in SPIFlash driver In some cases, SPIFlash driver hangs during initialization because it reads data from the SPI backend. But if SPI backend has not been initialized, this fails. --- libraries/MySensors/utility/SPIFlash.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/MySensors/utility/SPIFlash.cpp b/libraries/MySensors/utility/SPIFlash.cpp index 03d6a1a..ee6e1b0 100644 --- a/libraries/MySensors/utility/SPIFlash.cpp +++ b/libraries/MySensors/utility/SPIFlash.cpp @@ -56,6 +56,7 @@ void SPIFlash::unselect() { /// setup SPI, read device ID etc... boolean SPIFlash::initialize() { + SPI.begin(); _SPCR = SPCR; _SPSR = SPSR; pinMode(_slaveSelectPin, OUTPUT); From fcb92436d9abd3a86c9b74d6732a3c26c620e856 Mon Sep 17 00:00:00 2001 From: Marcelo Aquino Date: Thu, 9 Jul 2015 14:19:57 -0300 Subject: [PATCH 125/137] fix repeater loop for I_FIND_PARENT A repeater calls findParentNode() inside process() when receives a I_FIND_PARENT and nc.distance is invalid, this could cause a loop --- libraries/MySensors/MySensor.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 2e2d70e..099a927 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -302,6 +302,12 @@ void MySensor::setupNode() { } void MySensor::findParentNode() { + static boolean findingParentNode = false; + + if (findingParentNode) + return; + findingParentNode = true; + failedTransmissions = 0; // Set distance to max @@ -316,6 +322,7 @@ void MySensor::findParentNode() { // Wait for ping response. wait(2000); + findingParentNode = false; } boolean MySensor::sendRoute(MyMessage &message) { From 616b7d8b09e83aacf8821814765576204d85eaa7 Mon Sep 17 00:00:00 2001 From: "Bruce B. Lacey" Date: Sat, 11 Jul 2015 09:09:14 -0700 Subject: [PATCH 126/137] Changed the extended_fuses from 0xFE to 0x06 (set unused bits 3-7 to 0 instead of F) to improve compatibility with a broader range of programmers (e.g. ATMEL Dragon and USBTiny ISP v3). --- hardware/MySensors/avr/boards.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hardware/MySensors/avr/boards.txt b/hardware/MySensors/avr/boards.txt index 2a3c638..7fc0ec8 100644 --- a/hardware/MySensors/avr/boards.txt +++ b/hardware/MySensors/avr/boards.txt @@ -16,7 +16,7 @@ MysensorsMicro.bootloader.unlock_bits=0x3F MysensorsMicro.bootloader.lock_bits=0x0F MysensorsMicro.bootloader.low_fuses=0xE2 MysensorsMicro.bootloader.high_fuses=0xD2 -MysensorsMicro.bootloader.extended_fuses=0xFE +MysensorsMicro.bootloader.extended_fuses=0x06 MysensorsMicro.bootloader.file=DualOptiboot/optiboot_atmega328_pro_8MHz.hex MysensorsMicro.build.board=AVR_MICRO8 From 4abaa6ded34d22e3f3dd98d33d3d12450a537706 Mon Sep 17 00:00:00 2001 From: "Bruce B. Lacey" Date: Sat, 11 Jul 2015 09:31:30 -0700 Subject: [PATCH 127/137] Changed WITH_LEDS_BLINKING option to use the default LED pins as described on http://www.mysensors.org/build/advanced_gateway for consistency and backwards compatibility. Also corrected the LED on/off state to HIGH/LOW from LOW/HIGH respectively. --- libraries/MySensors/MyConfig.h | 6 +++--- libraries/MySensors/MySensor.cpp | 18 +++++++++--------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index c2148ab..11c8af1 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -58,11 +58,11 @@ // default LEDs blinking period in milliseconds #define DEFAULT_LED_BLINK_PERIOD 300 // The RX LED default pin -#define DEFAULT_RX_LED_PIN 8 +#define DEFAULT_RX_LED_PIN 6 // The TX LED default pin -#define DEFAULT_TX_LED_PIN 9 +#define DEFAULT_TX_LED_PIN 5 // The Error LED default pin -#define DEFAULT_ERR_LED_PIN 7 +#define DEFAULT_ERR_LED_PIN 4 /********************************** diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 2e2d70e..c32e44b 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -110,33 +110,33 @@ void MySensor::handleLedsBlinking() { // do the actual blinking if(countRx && countRx != 255) { // switch led on - digitalWrite(pinRx, LOW); + digitalWrite(pinRx, HIGH); } else if(!countRx) { // switching off - digitalWrite(pinRx, HIGH); + digitalWrite(pinRx, LOW); } if(countRx != 255) --countRx; if(countTx && countTx != 255) { // switch led on - digitalWrite(pinTx, LOW); + digitalWrite(pinTx, HIGH); } else if(!countTx) { // switching off - digitalWrite(pinTx, HIGH); + digitalWrite(pinTx, LOW); } if(countTx != 255) --countTx; if(countErr && countErr != 255) { // switch led on - digitalWrite(pinEr, LOW); + digitalWrite(pinEr, HIGH); } else if(!countErr) { // switching off - digitalWrite(pinEr, HIGH); + digitalWrite(pinEr, LOW); } if(countErr != 255) --countErr; @@ -182,9 +182,9 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b pinMode(pinEr, OUTPUT); // Set initial state of leds - digitalWrite(pinRx, HIGH); - digitalWrite(pinTx, HIGH); - digitalWrite(pinEr, HIGH); + digitalWrite(pinRx, LOW); + digitalWrite(pinTx, LOW); + digitalWrite(pinEr, LOW); // initialize counters countRx = 0; From 76493ff6a71771c47c0aae4e01d89a9aa088becb Mon Sep 17 00:00:00 2001 From: tekka007 Date: Tue, 21 Jul 2015 17:39:51 +0200 Subject: [PATCH 128/137] Sensebender OTA fix - fix OTA updates - update flash driver --- libraries/MySensors/MySensor.cpp | 60 ++++++---- libraries/MySensors/utility/SPIFlash.cpp | 142 +++++++++++++++-------- libraries/MySensors/utility/SPIFlash.h | 105 ++++++++++------- 3 files changed, 194 insertions(+), 113 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index c32e44b..b065d7c 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -74,24 +74,21 @@ MySensor::MySensor(MyTransport &_radio, MyHw &_hw #ifdef MY_OTA_FIRMWARE_FEATURE -// do a crc16 on the whole received firmware -bool MySensor::isValidFirmware() { - void* ptr = 0; - uint16_t crc = ~0; - int j; +// do a crc16 on the whole received firmware +bool MySensor::isValidFirmware() { + // init crc + uint16_t crc = ~0; for (uint16_t i = 0; i < fc.blocks * FIRMWARE_BLOCK_SIZE; ++i) { - uint8_t a = flash.readByte((uint16_t) ptr + i + FIRMWARE_START_OFFSET); - crc ^= a; - for (j = 0; j < 8; ++j) - { + crc ^= flash.readByte(i + FIRMWARE_START_OFFSET); + for (int8_t j = 0; j < 8; ++j) { if (crc & 1) crc = (crc >> 1) ^ 0xA001; else crc = (crc >> 1); } - } - return crc == fc.crc; + } + return crc == fc.crc; } #endif @@ -722,46 +719,61 @@ boolean MySensor::process() { // compare with current node configuration, if they differ, start fw fetch process if (memcmp(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig))) { debug(PSTR("fw update\n")); - fwUpdateOngoing = true; - fwBlock = fc.blocks; // copy new FW config memcpy(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig)); // Init flash if (!flash.initialize()) { debug(PSTR("flash init fail\n")); + fwUpdateOngoing = false; + } else { + // erase lower 32K -> max flash size for ATMEGA328 + flash.blockErase32K(0); + // wait until flash erased + while ( flash.busy() ); + fwBlock = fc.blocks; + fwUpdateOngoing = true; + // reset flags + fwRetry = MY_OTA_RETRY+1; + fwLastRequestTime = 0; } - - } + return false; + } else debug(PSTR("fw update skipped\n")); } else if (type == ST_FIRMWARE_RESPONSE) { - // Save block to eeprom + // Save block to flash debug(PSTR("fw block %d\n"), fwBlock); - + // extract FW block ReplyFWBlock *firmwareResponse = (ReplyFWBlock *)msg.data; // write to flash - flash.writeBytes(((fwBlock-1)*FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE); + flash.writeBytes( ((fwBlock - 1) * FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE); + // wait until flash written + while ( flash.busy() ); fwBlock--; - if (fwBlock == 0) { + if (!fwBlock) { // We're finished! Do a checksum and reboot. if (isValidFirmware()) { debug(PSTR("fw checksum ok\n")); // All seems ok, write size and signature to flash (DualOptiboot will pick this up and flash it) - uint16_t fwsize = FIRMWARE_BLOCK_SIZE*fc.blocks; flash.writeBytes(0, "FLXIMG:", 7); + // FW size in flash + uint16_t fwsize = FIRMWARE_BLOCK_SIZE * fc.blocks; flash.writeByte(7, fwsize >> 8); flash.writeByte(8, fwsize); + // end of header flash.writeByte(9, ':'); // Write the new firmware config to eeprom hw_writeConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig)); hw_reboot(); } else { debug(PSTR("fw checksum fail\n")); + fwUpdateOngoing = false; } } + // reset flags + fwRetry = MY_OTA_RETRY+1; + fwLastRequestTime = 0; + return false; } - // Make sure packet request occurs next time process() is called by timing out requestTime. - fwRetry = MY_OTA_RETRY+1; - fwLastRequestTime = 0; - return false; + } #endif // Call incoming message callback if available diff --git a/libraries/MySensors/utility/SPIFlash.cpp b/libraries/MySensors/utility/SPIFlash.cpp index ee6e1b0..e250c17 100644 --- a/libraries/MySensors/utility/SPIFlash.cpp +++ b/libraries/MySensors/utility/SPIFlash.cpp @@ -1,20 +1,40 @@ -/* - * Copyright (c) 2013 by Felix Rusu - * SPI Flash memory library for arduino/moteino. - * This works with 256byte/page SPI flash memory - * For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) - * Minimal modifications should allow chips that have different page size but modifications - * DEPENDS ON: Arduino SPI library - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ +// Copyright (c) 2013-2015 by Felix Rusu, LowPowerLab.com +// SPI Flash memory library for arduino/moteino. +// This works with 256byte/page SPI flash memory +// For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) +// Minimal modifications should allow chips that have different page size but modifications +// DEPENDS ON: Arduino SPI library +// > Updated Jan. 5, 2015, TomWS1, modified writeBytes to allow blocks > 256 bytes and handle page misalignment. +// > Updated Feb. 26, 2015 TomWS1, added support for SPI Transactions (Arduino 1.5.8 and above) +// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4 +// ********************************************************************************** +// License +// ********************************************************************************** +// This program is free software; you can redistribute it +// and/or modify it under the terms of the GNU General +// Public License as published by the Free Software +// Foundation; either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will +// be useful, but WITHOUT ANY WARRANTY; without even the +// implied warranty of MERCHANTABILITY or FITNESS FOR A +// PARTICULAR PURPOSE. See the GNU General Public +// License for more details. +// +// You should have received a copy of the GNU General +// Public License along with this program. +// If not, see . +// +// Licence can be viewed at +// http://www.gnu.org/licenses/gpl-3.0.txt +// +// Please maintain this license information along with authorship +// and copyright notices in any redistribution of this code #include -byte SPIFlash::UNIQUEID[8]; +uint8_t SPIFlash::UNIQUEID[8]; /// IMPORTANT: NAND FLASH memory requires erase before write, because /// it can only transition from 1s to 0s and only the erase command can reset all 0s to 1s @@ -32,15 +52,22 @@ SPIFlash::SPIFlash(uint8_t slaveSelectPin, uint16_t jedecID) { /// Select the flash chip void SPIFlash::select() { - noInterrupts(); //save current SPI settings +#ifndef SPI_HAS_TRANSACTION + noInterrupts(); +#endif _SPCR = SPCR; _SPSR = SPSR; - //set FLASH chip SPI settings + +#ifdef SPI_HAS_TRANSACTION + SPI.beginTransaction(_settings); +#else + // set FLASH SPI settings SPI.setDataMode(SPI_MODE0); SPI.setBitOrder(MSBFIRST); SPI.setClockDivider(SPI_CLOCK_DIV4); //decided to slow down from DIV2 after SPI stalling in some instances, especially visible on mega1284p when RFM69 and FLASH chip both present SPI.begin(); +#endif digitalWrite(_slaveSelectPin, LOW); } @@ -48,18 +75,25 @@ void SPIFlash::select() { void SPIFlash::unselect() { digitalWrite(_slaveSelectPin, HIGH); //restore SPI settings to what they were before talking to the FLASH chip +#ifdef SPI_HAS_TRANSACTION + SPI.endTransaction(); +#else + interrupts(); +#endif SPCR = _SPCR; SPSR = _SPSR; - interrupts(); } /// setup SPI, read device ID etc... boolean SPIFlash::initialize() { - SPI.begin(); _SPCR = SPCR; _SPSR = SPSR; pinMode(_slaveSelectPin, OUTPUT); +#ifdef SPI_HAS_TRANSACTION + _settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); +#endif + unselect(); wakeup(); @@ -73,7 +107,7 @@ boolean SPIFlash::initialize() } /// Get the manufacturer and device ID bytes (as a short word) -word SPIFlash::readDeviceId() +uint16_t SPIFlash::readDeviceId() { #if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo command(SPIFLASH_IDREAD); // Read JEDEC ID @@ -81,7 +115,7 @@ word SPIFlash::readDeviceId() select(); SPI.transfer(SPIFLASH_IDREAD); #endif - word jedecid = SPI.transfer(0) << 8; + uint16_t jedecid = SPI.transfer(0) << 8; jedecid |= SPI.transfer(0); unselect(); return jedecid; @@ -90,47 +124,47 @@ word SPIFlash::readDeviceId() /// Get the 64 bit unique identifier, stores it in UNIQUEID[8]. Only needs to be called once, ie after initialize /// Returns the byte pointer to the UNIQUEID byte array /// Read UNIQUEID like this: -/// flash.readUniqueId(); for (byte i=0;i<8;i++) { Serial.print(flash.UNIQUEID[i], HEX); Serial.print(' '); } +/// flash.readUniqueId(); for (uint8_t i=0;i<8;i++) { Serial.print(flash.UNIQUEID[i], HEX); Serial.print(' '); } /// or like this: -/// flash.readUniqueId(); byte* MAC = flash.readUniqueId(); for (byte i=0;i<8;i++) { Serial.print(MAC[i], HEX); Serial.print(' '); } -byte* SPIFlash::readUniqueId() +/// flash.readUniqueId(); uint8_t* MAC = flash.readUniqueId(); for (uint8_t i=0;i<8;i++) { Serial.print(MAC[i], HEX); Serial.print(' '); } +uint8_t* SPIFlash::readUniqueId() { command(SPIFLASH_MACREAD); SPI.transfer(0); SPI.transfer(0); SPI.transfer(0); SPI.transfer(0); - for (byte i=0;i<8;i++) + for (uint8_t i=0;i<8;i++) UNIQUEID[i] = SPI.transfer(0); unselect(); return UNIQUEID; } /// read 1 byte from flash memory -byte SPIFlash::readByte(long addr) { +uint8_t SPIFlash::readByte(uint32_t addr) { command(SPIFLASH_ARRAYREADLOWFREQ); SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); SPI.transfer(addr); - byte result = SPI.transfer(0); + uint8_t result = SPI.transfer(0); unselect(); return result; } /// read unlimited # of bytes -void SPIFlash::readBytes(long addr, void* buf, word len) { +void SPIFlash::readBytes(uint32_t addr, void* buf, uint16_t len) { command(SPIFLASH_ARRAYREAD); SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); SPI.transfer(addr); SPI.transfer(0); //"dont care" - for (word i = 0; i < len; ++i) - ((byte*) buf)[i] = SPI.transfer(0); + for (uint16_t i = 0; i < len; ++i) + ((uint8_t*) buf)[i] = SPI.transfer(0); unselect(); } /// Send a command to the flash chip, pass TRUE for isWrite when its a write command -void SPIFlash::command(byte cmd, boolean isWrite){ +void SPIFlash::command(uint8_t cmd, boolean isWrite){ #if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo DDRB |= B00000001; // Make sure the SS pin (PB0 - used by RFM12B on MoteinoLeo R1) is set as output HIGH! PORTB |= B00000001; @@ -156,7 +190,7 @@ boolean SPIFlash::busy() /* select(); SPI.transfer(SPIFLASH_STATUSREAD); - byte status = SPI.transfer(0); + uint8_t status = SPI.transfer(0); unselect(); return status & 1; */ @@ -164,11 +198,11 @@ boolean SPIFlash::busy() } /// return the STATUS register -byte SPIFlash::readStatus() +uint8_t SPIFlash::readStatus() { select(); SPI.transfer(SPIFLASH_STATUSREAD); - byte status = SPI.transfer(0); + uint8_t status = SPI.transfer(0); unselect(); return status; } @@ -177,7 +211,7 @@ byte SPIFlash::readStatus() /// Write 1 byte to flash memory /// WARNING: you can only write to previously erased memory locations (see datasheet) /// use the block erase commands to first clear memory (write 0xFFs) -void SPIFlash::writeByte(long addr, uint8_t byt) { +void SPIFlash::writeByte(uint32_t addr, uint8_t byt) { command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); @@ -186,20 +220,32 @@ void SPIFlash::writeByte(long addr, uint8_t byt) { unselect(); } -/// write 1-256 bytes to flash memory +/// write multiple bytes to flash memory (up to 64K) /// WARNING: you can only write to previously erased memory locations (see datasheet) /// use the block erase commands to first clear memory (write 0xFFs) -/// WARNING: if you write beyond a page boundary (or more than 256bytes), -/// the bytes will wrap around and start overwriting at the beginning of that same page -/// see datasheet for more details -void SPIFlash::writeBytes(long addr, const void* buf, uint16_t len) { - command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program - SPI.transfer(addr >> 16); - SPI.transfer(addr >> 8); - SPI.transfer(addr); - for (uint16_t i = 0; i < len; i++) - SPI.transfer(((byte*) buf)[i]); - unselect(); +/// This version handles both page alignment and data blocks larger than 256 bytes. +/// +void SPIFlash::writeBytes(uint32_t addr, const void* buf, uint16_t len) { + uint16_t n; + uint16_t maxBytes = 256-(addr%256); // force the first set of bytes to stay within the first page + uint16_t offset = 0; + while (len>0) + { + n = (len<=maxBytes) ? len : maxBytes; + command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program + SPI.transfer(addr >> 16); + SPI.transfer(addr >> 8); + SPI.transfer(addr); + + for (uint16_t i = 0; i < n; i++) + SPI.transfer(((uint8_t*) buf)[offset + i]); + unselect(); + + addr+=n; // adjust the addresses and remaining bytes by what we've just transferred. + offset +=n; + len -= n; + maxBytes = 256; // now we can do up to 256 bytes per loop + } } /// erase entire flash memory array @@ -214,7 +260,7 @@ void SPIFlash::chipErase() { } /// erase a 4Kbyte block -void SPIFlash::blockErase4K(long addr) { +void SPIFlash::blockErase4K(uint32_t addr) { command(SPIFLASH_BLOCKERASE_4K, true); // Block Erase SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); @@ -223,7 +269,7 @@ void SPIFlash::blockErase4K(long addr) { } /// erase a 32Kbyte block -void SPIFlash::blockErase32K(long addr) { +void SPIFlash::blockErase32K(uint32_t addr) { command(SPIFLASH_BLOCKERASE_32K, true); // Block Erase SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); diff --git a/libraries/MySensors/utility/SPIFlash.h b/libraries/MySensors/utility/SPIFlash.h index f0c071a..a308760 100644 --- a/libraries/MySensors/utility/SPIFlash.h +++ b/libraries/MySensors/utility/SPIFlash.h @@ -1,16 +1,36 @@ -/* - * Copyright (c) 2013 by Felix Rusu - * SPI Flash memory library for arduino/moteino. - * This works with 256byte/page SPI flash memory - * For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) - * Minimal modifications should allow chips that have different page size but modifications - * DEPENDS ON: Arduino SPI library - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ +// Copyright (c) 2013-2015 by Felix Rusu, LowPowerLab.com +// SPI Flash memory library for arduino/moteino. +// This works with 256byte/page SPI flash memory +// For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) +// Minimal modifications should allow chips that have different page size but modifications +// DEPENDS ON: Arduino SPI library +// > Updated Jan. 5, 2015, TomWS1, modified writeBytes to allow blocks > 256 bytes and handle page misalignment. +// > Updated Feb. 26, 2015 TomWS1, added support for SPI Transactions (Arduino 1.5.8 and above) +// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4 +// ********************************************************************************** +// License +// ********************************************************************************** +// This program is free software; you can redistribute it +// and/or modify it under the terms of the GNU General +// Public License as published by the Free Software +// Foundation; either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will +// be useful, but WITHOUT ANY WARRANTY; without even the +// implied warranty of MERCHANTABILITY or FITNESS FOR A +// PARTICULAR PURPOSE. See the GNU General Public +// License for more details. +// +// You should have received a copy of the GNU General +// Public License along with this program. +// If not, see . +// +// Licence can be viewed at +// http://www.gnu.org/licenses/gpl-3.0.txt +// +// Please maintain this license information along with authorship +// and copyright notices in any redistribution of this code #ifndef _SPIFLASH_H_ #define _SPIFLASH_H_ @@ -33,19 +53,19 @@ /// Assuming the WP pin is pulled up (to disable hardware write protection) /// To use any write commands the WEL bit in the status register must be set to 1. /// This is accomplished by sending a 0x06 command before any such write/erase command. -/// The WEL bit in the status register resets to the logical “0” state after a -/// device power-up or reset. In addition, the WEL bit will be reset to the logical “0” state automatically under the following conditions: -/// • Write Disable operation completes successfully -/// • Write Status Register operation completes successfully or aborts -/// • Protect Sector operation completes successfully or aborts -/// • Unprotect Sector operation completes successfully or aborts -/// • Byte/Page Program operation completes successfully or aborts -/// • Sequential Program Mode reaches highest unprotected memory location -/// • Sequential Program Mode reaches the end of the memory array -/// • Sequential Program Mode aborts -/// • Block Erase operation completes successfully or aborts -/// • Chip Erase operation completes successfully or aborts -/// • Hold condition aborts +/// The WEL bit in the status register resets to the logical ?0? state after a +/// device power-up or reset. In addition, the WEL bit will be reset to the logical ?0? state automatically under the following conditions: +/// ? Write Disable operation completes successfully +/// ? Write Status Register operation completes successfully or aborts +/// ? Protect Sector operation completes successfully or aborts +/// ? Unprotect Sector operation completes successfully or aborts +/// ? Byte/Page Program operation completes successfully or aborts +/// ? Sequential Program Mode reaches highest unprotected memory location +/// ? Sequential Program Mode reaches the end of the memory array +/// ? Sequential Program Mode aborts +/// ? Block Erase operation completes successfully or aborts +/// ? Chip Erase operation completes successfully or aborts +/// ? Hold condition aborts #define SPIFLASH_WRITEENABLE 0x06 // write enable #define SPIFLASH_WRITEDISABLE 0x04 // write disable @@ -69,21 +89,21 @@ class SPIFlash { public: - static byte UNIQUEID[8]; - SPIFlash(byte slaveSelectPin, uint16_t jedecID=0); + static uint8_t UNIQUEID[8]; + SPIFlash(uint8_t slaveSelectPin, uint16_t jedecID=0); boolean initialize(); - void command(byte cmd, boolean isWrite=false); - byte readStatus(); - byte readByte(long addr); - void readBytes(long addr, void* buf, word len); - void writeByte(long addr, byte byt); - void writeBytes(long addr, const void* buf, uint16_t len); + void command(uint8_t cmd, boolean isWrite=false); + uint8_t readStatus(); + uint8_t readByte(uint32_t addr); + void readBytes(uint32_t addr, void* buf, uint16_t len); + void writeByte(uint32_t addr, uint8_t byt); + void writeBytes(uint32_t addr, const void* buf, uint16_t len); boolean busy(); void chipErase(); - void blockErase4K(long address); - void blockErase32K(long address); - word readDeviceId(); - byte* readUniqueId(); + void blockErase4K(uint32_t address); + void blockErase32K(uint32_t address); + uint16_t readDeviceId(); + uint8_t* readUniqueId(); void sleep(); void wakeup(); @@ -91,10 +111,13 @@ public: protected: void select(); void unselect(); - byte _slaveSelectPin; + uint8_t _slaveSelectPin; uint16_t _jedecID; - byte _SPCR; - byte _SPSR; + uint8_t _SPCR; + uint8_t _SPSR; +#ifdef SPI_HAS_TRANSACTION + SPISettings _settings; +#endif }; #endif \ No newline at end of file From a22f712d60fd2cb404c5ab509dcb7405ec7332b1 Mon Sep 17 00:00:00 2001 From: Marcelo Aquino Date: Tue, 28 Jul 2015 11:32:52 -0300 Subject: [PATCH 129/137] respond to a I_FIND_PARENT after findParentNode() When a repeater receives a I_FIND_PARENT, it first update the nc.distance if is invalid and then respond the request --- libraries/MySensors/MySensor.cpp | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 099a927..19b03c4 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -781,14 +781,17 @@ boolean MySensor::process() { // If this node have an id, relay the message if (command == C_INTERNAL && type == I_FIND_PARENT) { - if (nc.distance == DISTANCE_INVALID) { - findParentNode(); - } else if (sender != nc.parentNodeId) { - // Relaying nodes should always answer ping messages - // Wait a random delay of 0-2 seconds to minimize collision - // between ping ack messages from other relaying nodes - wait(hw_millis() & 0x3ff); - sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance)); + if (sender != nc.parentNodeId) { + if (nc.distance == DISTANCE_INVALID) + findParentNode(); + + if (nc.distance != DISTANCE_INVALID) { + // Relaying nodes should always answer ping messages + // Wait a random delay of 0-2 seconds to minimize collision + // between ping ack messages from other relaying nodes + wait(hw_millis() & 0x3ff); + sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance)); + } } } else if (to == nc.nodeId) { // We should try to relay this message to another node From 79c4cee47535dba34d18ed84e023e14c1bd24e19 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 28 Jul 2015 19:44:46 +0200 Subject: [PATCH 130/137] Fix signing problem reported by @scalz http://forum.mysensors.org/topic/1021/security-introducing-signing-support-to-mysensors/103 --- libraries/MySensors/MySensor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index b065d7c..6949e83 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -343,7 +343,7 @@ boolean MySensor::sendRoute(MyMessage &message) { #ifdef MY_SIGNING_FEATURE // If destination is known to require signed messages and we are the sender, sign this message unless it is an ACK or a handshake message - if (DO_SIGN(message.destination) && message.sender == nc.nodeId && !mGetAck(message) && mGetLength(msg) && + if (DO_SIGN(message.destination) && message.sender == nc.nodeId && !mGetAck(message) && mGetLength(message) && (mGetCommand(message) != C_INTERNAL || (message.type != I_GET_NONCE && message.type != I_GET_NONCE_RESPONSE && message.type != I_REQUEST_SIGNING && message.type != I_ID_REQUEST && message.type != I_ID_RESPONSE && From 5bab725f81a98cd47d15c731a2d70754a8f229bc Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 30 Jul 2015 14:41:57 +0200 Subject: [PATCH 131/137] Bump version to 1.5 --- libraries/MySensors/Version.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/Version.h b/libraries/MySensors/Version.h index 437cd2c..c782265 100644 --- a/libraries/MySensors/Version.h +++ b/libraries/MySensors/Version.h @@ -6,6 +6,6 @@ #ifndef Version_h #define Version_h -#define LIBRARY_VERSION "1.5 b1" +#define LIBRARY_VERSION "1.5" #endif From 34ace0bad7c6b4c1539e007dfb01ab5f801d7282 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 30 Jul 2015 20:58:50 +0200 Subject: [PATCH 132/137] Fix spelling error on setpoint cool --- libraries/MySensors/MyMessage.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index 6dc504b..129801f 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -86,8 +86,8 @@ typedef enum { typedef enum { V_TEMP, // S_TEMP V_HUM, // S_HUM - V_STATUS, // S_LIGHT, S_DIMMER, S_SPRINKLER, Used for setting binary (on/off) status. 1=on, 0=off - V_LIGHT=2, // S_LIGHT, S_DIMMER. Same as V_STATUS + V_STATUS, // S_LIGHT, S_DIMMER, S_SPRINKLER, S_HVAC, S_HEATER. Used for setting binary (on/off) status. 1=on, 0=off + V_LIGHT=2, // Same as V_STATUS V_PERCENTAGE, // S_DIMMER. Used for sending a percentage value (0-100). V_DIMMER=3, // S_DIMMER. Same as V_PERCENTAGE. V_PRESSURE, // S_BARO @@ -110,7 +110,7 @@ typedef enum { V_HEATER, // Deprecated. Use V_HVAC_FLOW_STATE instead. V_HVAC_FLOW_STATE=21, // HVAC flow state ("Off", "HeatOn", "CoolOn", or "AutoChangeOver"). S_HEATER, S_HVAC V_HVAC_SPEED, // HVAC/Heater fan speed ("Min", "Normal", "Max", "Auto") - V_LIGHT_LEVEL, // S_LIGHT_LEVEL (light level in uncalibrated percentage) or S_LEVEL (light level in lux) + V_LIGHT_LEVEL, // Used for sending light level in uncalibrated percentage. See also V_LEVEL (light level in lux). S_LIGHT_LEVEL V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, V_UP, // S_COVER V_DOWN, // S_COVER @@ -134,7 +134,7 @@ typedef enum { V_UNIT_PREFIX, // Allows sensors to send in a string representing the // unit prefix to be displayed in GUI, not parsed by controller! E.g. cm, m, km, inch. // Can be used for S_DISTANCE or gas concentration (S_DUST, S_AIR_QUALITY) - V_HVAC_SETPOINT_COLD, // HVAC cold setpoint (Integer between 0-100). S_HVAC + V_HVAC_SETPOINT_COOL, // HVAC cool setpoint (Integer between 0-100). S_HVAC V_HVAC_SETPOINT_HEAT, // HVAC/Heater setpoint (Integer between 0-100). S_HEATER, S_HVAC V_HVAC_FLOW_MODE, // Flow mode for HVAC ("Auto", "ContinuousOn", "PeriodicOn"). S_HVAC From 237b080b2eeb3b0858b602a43099888036ffe6f9 Mon Sep 17 00:00:00 2001 From: Barduino Date: Thu, 30 Jul 2015 15:04:02 -0400 Subject: [PATCH 133/137] Create MockMySensors Arduino sketch to mock sensors for the MySensors Library This skecth is intended to crate fake sensors which register and respond to the controller Barduino 2015 ----------------- Comment/Uncomment the sensors you would like to test Arduino Uno R3 can support about 12 sensors before it runs out of memory. You probably need to turn of the MySensor Lib debug to save some memory Nest step will be to remove the read/write to the eprom and extend to support the v1.5 sensors --- libraries/MySensors/examples/MockMySensors | 1018 ++++++++++++++++++++ 1 file changed, 1018 insertions(+) create mode 100644 libraries/MySensors/examples/MockMySensors diff --git a/libraries/MySensors/examples/MockMySensors b/libraries/MySensors/examples/MockMySensors new file mode 100644 index 0000000..4397208 --- /dev/null +++ b/libraries/MySensors/examples/MockMySensors @@ -0,0 +1,1018 @@ +/* +* FakeMySensors +* +* This skecth is intended to crate fake sensors which register and respond to the controller +* +* Barduino 2015 +*/ + +#include +#include + +// SPI Pins +#define CE_PIN 9 +#define CS_PIN 10 + +// Wait times +#define LONG_WAIT 500 +#define SHORT_WAIT 50 + +#define SKETCH_NAME "FakeMySensors " +#define SKETCH_VERSION "v0.2" + +// Define Sensors ids +/* S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, + S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, + S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, + S_SCENE_CONTROLLER +*/ + +////#define ID_S_ARDUINO_NODE //auto defined in initialization +////#define ID_S_ARDUINO_REPEATER_NODE //auto defined in initialization + +//#define ID_S_DOOR 1 +//#define ID_S_MOTION 2 +//#define ID_S_SMOKE 3 +//#define ID_S_LIGHT 4 +//#define ID_S_DIMMER 5 +//#define ID_S_COVER 6 +//#define ID_S_TEMP 7 +//#define ID_S_HUM 8 +//#define ID_S_BARO 9 +//#define ID_S_WIND 10 +//#define ID_S_RAIN 11 +//#define ID_S_UV 12 +//#define ID_S_WEIGHT 13 +#define ID_S_POWER 14 +#define ID_S_HEATER 15 +#define ID_S_DISTANCE 16 +#define ID_S_LIGHT_LEVEL 17 +#define ID_S_LOCK 18 +#define ID_S_IR 19 +#define ID_S_WATER 20 +#define ID_S_AIR_QUALITY 21 +#define ID_S_DUST 22 +#define ID_S_SCENE_CONTROLLER 23 + +#define ID_S_CUSTOM 24 + +// Global Vars +unsigned long SLEEP_TIME = 60000; // Sleep time between reads (in milliseconds) +boolean metric = true; +long randNumber; + +// Instanciate MySersors Gateway +MySensor gw(CE_PIN,CS_PIN); + +//Instanciate Messages objects + +#ifdef ID_S_DOOR + MyMessage msg_S_DOOR(ID_S_DOOR,V_TRIPPED); +#endif + +#ifdef ID_S_MOTION + MyMessage msg_S_MOTION_A(ID_S_MOTION,V_ARMED); + MyMessage msg_S_MOTION_T(ID_S_MOTION,V_TRIPPED); +#endif + +#ifdef ID_S_SMOKE + MyMessage msg_S_SMOKE(ID_S_SMOKE,V_TRIPPED); +#endif + +#ifdef ID_S_LIGHT + MyMessage msg_S_LIGHT(ID_S_LIGHT,V_LIGHT); +#endif + +#ifdef ID_S_DIMMER + MyMessage msg_S_DIMMER(ID_S_DIMMER,V_DIMMER); +#endif + +#ifdef ID_S_COVER + MyMessage msg_S_COVER_U(ID_S_COVER,V_UP); + MyMessage msg_S_COVER_D(ID_S_COVER,V_DOWN); + MyMessage msg_S_COVER_S(ID_S_COVER,V_STOP); +#endif + +#ifdef ID_S_TEMP + MyMessage msg_S_TEMP(ID_S_TEMP,V_TEMP); +#endif + +#ifdef ID_S_HUM + MyMessage msg_S_HUM(ID_S_HUM,V_HUM); +#endif + +#ifdef ID_S_BARO + MyMessage msg_S_BARO_P(ID_S_BARO,V_PRESSURE); + MyMessage msg_S_BARO_F(ID_S_BARO,V_FORECAST); +#endif + +#ifdef ID_S_WIND + MyMessage msg_S_WIND_S(ID_S_WIND,V_WIND); + MyMessage msg_S_WIND_G(ID_S_WIND,V_GUST); + MyMessage msg_S_WIND_D(ID_S_WIND,V_DIRECTION); +#endif + +#ifdef ID_S_RAIN + MyMessage msg_S_RAIN_A(ID_S_RAIN,V_RAIN); + MyMessage msg_S_RAIN_R(ID_S_RAIN,V_RAINRATE); +#endif + +#ifdef ID_S_UV + MyMessage msg_S_UV(ID_S_UV,V_UV); +#endif + +#ifdef ID_S_WEIGHT + MyMessage msg_S_WEIGHT(ID_S_WEIGHT,V_WEIGHT); +#endif + +#ifdef ID_S_POWER + MyMessage msg_S_POWER_I(ID_S_POWER,V_IMPEDANCE); + MyMessage msg_S_POWER_W(ID_S_POWER,V_WATT); + MyMessage msg_S_POWER_K(ID_S_POWER,V_KWH); + MyMessage msg_S_POWER_V(ID_S_POWER,V_VOLTAGE); + MyMessage msg_S_POWER_C(ID_S_POWER,V_CURRENT); +#endif + +#ifdef ID_S_HEATER + MyMessage msg_S_HEATER_M(ID_S_HEATER,V_HEATER); + MyMessage msg_S_HEATER_S(ID_S_HEATER,V_HEATER_SW); +#endif + +#ifdef ID_S_DISTANCE + MyMessage msg_S_DISTANCE(ID_S_DISTANCE,V_DISTANCE); +#endif + +#ifdef ID_S_LIGHT_LEVEL + MyMessage msg_S_LIGHT_LEVEL(ID_S_LIGHT_LEVEL,V_LIGHT_LEVEL); +#endif + +#ifdef ID_S_LOCK + MyMessage msg_S_LOCK(ID_S_LOCK,V_LOCK_STATUS); +#endif + +#ifdef ID_S_IR + MyMessage msg_S_IR_S(ID_S_IR,V_IR_SEND); + MyMessage msg_S_IR_R(ID_S_IR,V_IR_RECEIVE); +#endif + +#ifdef ID_S_WATER + MyMessage msg_S_WATER_F(ID_S_WATER,V_FLOW); + MyMessage msg_S_WATER_V(ID_S_WATER,V_VOLUME); +#endif + +#ifdef ID_S_AIR_QUALITY + MyMessage msg_S_AIR_QUALITY(ID_S_AIR_QUALITY,V_VAR1); +#endif + +#ifdef ID_S_DUST + MyMessage msg_S_DUST(ID_S_DUST,V_DUST_LEVEL); +#endif + +#ifdef ID_S_SCENE_CONTROLLER + MyMessage msg_S_SCENE_CONTROLLER_ON(ID_S_SCENE_CONTROLLER,V_SCENE_ON); + MyMessage msg_S_SCENE_CONTROLLER_OF(ID_S_SCENE_CONTROLLER,V_SCENE_OFF); +#endif + +#ifdef ID_S_CUSTOM + MyMessage msg_S_CUSTOM_2(ID_S_CUSTOM,V_VAR2); + MyMessage msg_S_CUSTOM_3(ID_S_CUSTOM,V_VAR3); + MyMessage msg_S_CUSTOM_4(ID_S_CUSTOM,V_VAR4); + MyMessage msg_S_CUSTOM_5(ID_S_CUSTOM,V_VAR5); +#endif + + + + +void setup() +{ + // Random SEED + randomSeed(analogRead(0)); + + // Start the gateway + gw.begin(incomingMessage,254); + gw.wait(LONG_WAIT); + Serial.println("GW Started"); + + // Send the Sketch Version Information to the Gateway + Serial.print("Send Sketch Info: "); + gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION); + Serial.print(SKETCH_NAME); + Serial.println(SKETCH_VERSION); + gw.wait(LONG_WAIT); + + // Get controller configuration + Serial.print("Get Config: "); + metric = gw.getConfig().isMetric; + Serial.println(metric ? "Metric":"Imperial"); + gw.wait(LONG_WAIT); + + // Register all sensors to gw (they will be created as child devices) + Serial.println("Presenting Nodes"); + Serial.println("________________"); + + #ifdef ID_S_DOOR + Serial.println(" S_DOOR"); + gw.present(ID_S_DOOR,S_DOOR); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_MOTION + Serial.println(" S_MOTION"); + gw.present(ID_S_MOTION,S_MOTION); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_SMOKE + Serial.println(" S_SMOKE"); + gw.present(ID_S_SMOKE,S_SMOKE); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LIGHT + Serial.println(" S_LIGHT"); + gw.present(ID_S_LIGHT,S_LIGHT); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DIMMER + Serial.println(" S_DIMMER"); + gw.present(ID_S_DIMMER,S_DIMMER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_COVER + Serial.println(" S_COVER"; + gw.present(ID_S_COVER,S_COVER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_TEMP + Serial.println(" S_TMEP"); + gw.present(ID_S_TEMP,S_TEMP); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_HUM + Serial.println(" S_HUM"); + gw.present(ID_S_HUM,S_HUM); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_BARO + Serial.println(" S_BARO"); + gw.present(ID_S_BARO,S_BARO); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WIND + Serial.println(" S_WIND"); + gw.present(ID_S_WIND,S_WIND); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_RAIN + Serial.println(" S_RAIN"); + gw.present(ID_S_RAIN,S_RAIN); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_UV + Serial.println(" S_UV"); + gw.present(ID_S_UV,S_UV); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WEIGHT + Serial.println(" S_WEIGHT"): + gw.present(ID_S_WEIGHT,S_WEIGHT); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_POWER + Serial.println(" S_POWER"); + gw.present(ID_S_POWER,S_POWER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_HEATER + Serial.println(" S_HEATER"); + gw.present(ID_S_HEATER,S_HEATER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DISTANCE + Serial.println(" S_DISTANCE"); + gw.present(ID_S_DISTANCE,S_DISTANCE); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LIGHT_LEVEL + Serial.println(" S_LIGHT_LEVEL"); + gw.present(ID_S_LIGHT_LEVEL,S_LIGHT_LEVEL); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LOCK + Serial.println(" S_LOCK"); + gw.present(ID_S_LOCK,S_LOCK); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_IR + Serial.println(" S_IR"); + gw.present(ID_S_IR,S_IR); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WATER + Serial.println(" S_WATER"); + gw.present(ID_S_WATER,S_WATER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_AIR_QUALITY + Serial.println(" S_AIR_QUALITY"); + gw.present(ID_S_AIR_QUALITY,S_AIR_QUALITY); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DUST + Serial.println(" S_DUST"); + gw.present(ID_S_DUST,S_DUST); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_SCENE_CONTROLLER + Serial.println(" S_SCENE_CONTROLLER"); + gw.present(ID_S_SCENE_CONTROLLER,S_SCENE_CONTROLLER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_CUSTOM + Serial.println(" S_CUSTOM"); + gw.present(ID_S_CUSTOM,S_CUSTOM); + gw.wait(SHORT_WAIT); + #endif + + + +Serial.println("________________"); + +} + +void loop() +{ + Serial.println(""); + Serial.println(""); + Serial.println(""); + Serial.println("#########################"); + randNumber=random(0,101); + + Serial.print("RandomNumber:"); + Serial.println(randNumber); + // Send fake battery level + Serial.println("Send Battery Level"); + gw.sendBatteryLevel(randNumber); + gw.wait(LONG_WAIT); + + // Request time + Serial.println("Request Time"); + gw.requestTime(receiveTime); + gw.wait(LONG_WAIT); + + //Read Sensors + #ifdef S_ID_DOOR + door(); + #endif + + #ifdef ID_S_MOTION + motion(); + #endif + + #ifdef ID_S_SMOKE + smoke(); + #endif + + #ifdef ID_S_LIGHT + light(); + #endif + + #ifdef ID_S_DIMMER + dimmer(); + #endif + + #ifdef ID_S_COVER + cover(); + #endif + + #ifdef ID_S_TEMP + temp(); + #endif + + #ifdef ID_S_HUM + hum(); + #endif + + #ifdef ID_S_BARO + baro(); + #endif + + #ifdef ID_S_WIND + wind(); + #endif + + #ifdef ID_S_RAIN + rain(); + #endif + + #ifdef ID_S_UV + uv(); + #endif + + #ifdef ID_S_WEIGHT + weight(); + #endif + + #ifdef ID_S_POWER + power(); + #endif + + #ifdef ID_S_HEATER + heater(); + #endif + + #ifdef ID_S_DISTANCE + distance(); + #endif + + #ifdef ID_S_LIGHT_LEVEL + light_level(); + #endif + + #ifdef ID_S_LOCK + lock(); + #endif + + #ifdef ID_S_IR + ir(); + #endif + + #ifdef ID_S_WATER + water(); + #endif + + #ifdef ID_S_AIR_QUALITY + air(); + #endif + + #ifdef ID_S_DUST + dust(); + #endif + + #ifdef ID_S_SCENE_CONTROLLER + scene(); + #endif + + #ifdef ID_S_CUSTOM + custom(); + #endif + + gw.sendBatteryLevel(randNumber); + gw.wait(SHORT_WAIT); + gw.process(); + Serial.println("#########################"); + gw.wait(SLEEP_TIME); //sleep a bit +} + +// This is called when a new time value was received +void receiveTime(unsigned long controllerTime) { + + Serial.print("Time value received: "); + Serial.println(controllerTime); + +} + +//void door(){} + +#ifdef S_ID_DOOR +void door(){ + + Serial.print("Door is: " ); + + if (randNumber <= 50) { + Serial.println("Open"); + gw.send(msg_S_DOOR.set(1)); + } else { + Serial.println("Closed"); + gw.send(msg_S_DOOR.set(0)); + } + +} +#endif + +#ifdef ID_S_MOTION +void motion(){ + + Serial.print("Motion is: " ); + + if (randNumber <= 50) { + Serial.println("Active"); + gw.send(msg_S_MOTION_T.set(1)); + } else { + Serial.println("Quiet"); + gw.send(msg_S_MOTION_T.set(0)); + } + +} +#endif + +#ifdef ID_S_SMOKE +void smoke(){ + + Serial.print("Smoke is: " ); + + if (randNumber <= 50) { + Serial.println("Active"); + gw.send(msg_S_SMOKE.set(1)); + } else { + Serial.println("Quiet"); + gw.send(msg_S_SMOKE.set(0)); + } + +} +#endif + +#ifdef ID_S_LIGHT +void light(){ + + bool isLightOn = gw.loadState(ID_S_LIGHT); + + Serial.print("Light is: " ); + + if (isLightOn) { + Serial.println("On"); + gw.send(msg_S_LIGHT.set(1)); + } else { + Serial.println("Off"); + gw.send(msg_S_LIGHT.set(0)); + } + +} +#endif + +#ifdef ID_S_DIMMER +void dimmer(){ + + int dimmerVal = gw.loadState(ID_S_DIMMER); + + Serial.print("Dimmer is set to: " ); + Serial.println(dimmerVal); + + gw.send(msg_S_DIMMER.set(dimmerVal)); + +} +#endif + +#ifdef ID_S_COVER +void cover(){ + + int coverVal = gw.loadState(ID_S_COVER); + + Serial.print("Cover is : " ); + + switch (coverVal) { + case 0: + Serial.println("Opening"); + gw.send(msg_S_COVER_U.set(V_UP)); + break; + case 1: + Serial.println("Closing"); + gw.send(msg_S_COVER_D.set(V_DOWN)); + break; + default: + Serial.println("Idle"); + gw.send(msg_S_COVER_S.set(V_STOP)); + } + +} +#endif + +#ifdef ID_S_TEMP +void temp(){ + + Serial.print("Temperature is: " ); + Serial.println(map(randNumber,1,100,0,45)); + + gw.send(msg_S_TEMP.set(map(randNumber,1,100,0,45))); + +} +#endif + +#ifdef ID_S_HUM +void hum(){ + + Serial.print("Humitidty is: " ); + Serial.println(randNumber); + + gw.send(msg_S_HUM.set(randNumber)); + +} +#endif + +#ifdef ID_S_BARO +void baro(){ + + const char *weather[] = {"stable","sunny","cloudy","unstable","thunderstorm","unknown"}; + long pressure = map(randNumber,1,100,87000,108600); + int forecast = map(randNumber,1,100,0,5); + + Serial.print("Atmosferic Pressure is: " ); + Serial.println(pressure); + gw.send(msg_S_BARO_P.set(pressure)); + + Serial.print("Weather forecast: " ); + Serial.println(weather[forecast]); + gw.send(msg_S_BARO_F.set(weather[forecast])); + +} +#endif + +#ifdef ID_S_WIND +void wind(){ + + Serial.print("Wind Speed is: " ); + Serial.println(randNumber); + gw.send(msg_S_WIND_S.set(randNumber)); + + Serial.print("Wind Gust is: " ); + Serial.println(randNumber+10); + gw.send(msg_S_WIND_G.set(randNumber+10)); + + Serial.print("Wind Direction is: " ); + Serial.println(map(randNumber,1,100,0,360)); + gw.send(msg_S_WIND_D.set(map(randNumber,1,100,0,360))); + +} +#endif + +#ifdef ID_S_RAIN +void rain(){ + + Serial.print("Rain ammount is: " ); + Serial.println(randNumber); + + gw.send(msg_S_RAIN_A.set(randNumber)); + + Serial.print("Rain rate is: " ); + Serial.println(randNumber/60); + + gw.send(msg_S_RAIN_R.set(randNumber/60,1)); + +} +#endif + +#ifdef ID_S_UV +void uv(){ + + Serial.print("Ultra Violet level is: " ); + Serial.println(map(randNumber,1,100,0,15)); + + gw.send(msg_S_UV.set(map(randNumber,1,100,0,15))); + +} +#endif + +#ifdef ID_S_WEIGHT +void weight(){ + + Serial.print("Weight is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WEIGHT.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_POWER +void power(){ + + Serial.print("Impedance is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_I.set(map(randNumber,1,100,0,150))); + + Serial.print("Watt is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_W.set(map(randNumber,1,100,0,150))); + + Serial.print("KWH is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_K.set(map(randNumber,1,100,0,150))); + + Serial.print("Voltage is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_V.set(map(randNumber,1,100,0,150))); + + Serial.print("Current is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_C.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_HEATER +void heater(){ + int heater_mode = gw.loadState(ID_S_HEATER); + bool heater_switch = gw.loadState(ID_S_HEATER+1); + + Serial.print("Heater mode is: " ); + + if (heater_mode == 0){ + Serial.println("Off"); + } + else if (heater_mode == 1){ + Serial.println("Heat On"); + } + else if (heater_mode == 2){ + Serial.println("Cool On"); + } + else if (heater_mode == 3){ + Serial.println("Auto Change Over"); + } + else { + Serial.print("Unknown Heater Mode: "); + Serial.println(heater_mode); + } + + gw.send(msg_S_HEATER_M.set(heater_mode)); + + Serial.print("Heater is: " ); + Serial.println(heater_switch?"On":"Off"); + + gw.send(msg_S_HEATER_S.set(heater_switch)); + +} +#endif + +#ifdef ID_S_DISTANCE +void distance(){ + + Serial.print("Distance is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_DISTANCE.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_LIGHT_LEVEL +void light_level(){ + + Serial.print("Light is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_LIGHT_LEVEL.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_LOCK +void lock(){ + + bool isLocked = gw.loadState(ID_S_LOCK); + + Serial.print("Lock is: " ); + + if (isLocked) { + Serial.println("On"); + gw.send(msg_S_LOCK.set(1)); + } else { + Serial.println("Off"); + gw.send(msg_S_LOCK.set(0)); + } + +} +#endif + +#ifdef ID_S_IR +void ir(){ + + int irVal = gw.loadState(ID_S_IR); + + Serial.print("Infrared is: " ); + Serial.println(irVal); + + gw.send(msg_S_IR_S.set(irVal)); + +} +#endif + +#ifdef ID_S_WATER +void water(){ + + Serial.print("Water flow is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WATER_F.set(map(randNumber,1,100,0,150))); + + Serial.print("Water volume is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WATER_V.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_AIR_QUALITY +void air(){ + + Serial.print("Air Quality is: " ); + Serial.println(randNumber); + + gw.send(msg_S_AIR_QUALITY.set(randNumber)); + +} +#endif + +#ifdef ID_S_DUST +void dust(){ + + Serial.print("Dust level is: " ); + Serial.println(randNumber); + + gw.send(msg_S_DUST.set(randNumber)); + +} +#endif + +#ifdef ID_S_SCENE_CONTROLLER +void scene(){ + + bool isSceneOn = gw.loadState(ID_S_SCENE_CONTROLLER); + + Serial.print("Scene is: " ); + Serial.println(isSceneOn ? "On":"Off"); + + if(isSceneOn) + gw.send(msg_S_SCENE_CONTROLLER_ON.set(isSceneOn)); + else + gw.send(msg_S_SCENE_CONTROLLER_OF.set(isSceneOn)); + +} +#endif + +#ifdef ID_S_CUSTOM +void custom(){ + + Serial.print("Custom value is: " ); + Serial.println(randNumber); + + gw.send(msg_S_CUSTOM_2.set(randNumber)); + gw.send(msg_S_CUSTOM_3.set(randNumber)); + gw.send(msg_S_CUSTOM_4.set(randNumber)); + gw.send(msg_S_CUSTOM_5.set(randNumber)); + +} +#endif + + +void incomingMessage(const MyMessage &message) { + switch (message.type) { + #ifdef ID_S_LIGHT + case V_LIGHT: + gw.saveState(ID_S_LIGHT, message.getBool()); + Serial.print("Incoming change for ID_S_LIGHT:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getBool()); + break; + #endif + + #ifdef ID_S_DIMMER + case V_DIMMER: + if ((message.getInt()<0)||(message.getInt()>100)) { + Serial.println( "V_DIMMER data invalid (should be 0..100)" ); + break; + } + gw.saveState(ID_S_DIMMER, message.getInt()); + Serial.print("Incoming change for ID_S_DIMMER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getInt()); + break; + #endif + + #ifdef ID_S_COVER + case V_UP: + gw.saveState(ID_S_COVER, 0); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_UP"); + break; + + case V_DOWN: + gw.saveState(ID_S_COVER, 1); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_DOWN"); + break; + + case V_STOP: + gw.saveState(ID_S_COVER, 2); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_STOP"); + break; + #endif + + #ifdef ID_S_HEATER + case V_HEATER: + gw.saveState(ID_S_HEATER, message.getInt()); + Serial.print("Incoming change for ID_S_HEATER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + + if (message.getInt() == 0){ + Serial.println("Off"); + } + else if (message.getInt() == 1){ + Serial.println("Heat On"); + } + else if (message.getInt() == 2){ + Serial.println("Cool On"); + } + else if (message.getInt() == 3){ + Serial.println("Auto Change Over"); + } + else { + Serial.print("Unknown Heater Mode: "); + Serial.println(message.getInt()); + } + break; + + case V_HEATER_SW: + gw.saveState(ID_S_HEATER+1, message.getBool()); + Serial.print("Incoming change for ID_S_HEATER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println((message.getBool() ? "On":"Off")); + break; + #endif + + #ifdef ID_S_LOCK + case V_LOCK_STATUS: + gw.saveState(ID_S_LOCK, message.getBool()); + Serial.print("Incoming change for ID_S_LOCK:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getBool()?"Locked":"Unlocked"); + break; + #endif + + #ifdef ID_S_IR + case V_IR_RECEIVE: + gw.saveState(ID_S_IR, message.getInt()); + Serial.print("Incoming change for ID_S_IR:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getInt()); + break; + #endif + + #ifdef ID_S_SCENE_CONTROLLER + case V_SCENE_ON: + gw.saveState(ID_S_SCENE_CONTROLLER, 1); + Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("On"); + break; + case V_SCENE_OFF: + gw.saveState(ID_S_SCENE_CONTROLLER, 0); + Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("Off"); + break; + #endif + + default: + Serial.print("Unknown/UnImplemented message type:"); + Serial.println(message.type); + } + +} + + + + + + + From 0b2aa6dd16582bd47fd12071284262ce436bce97 Mon Sep 17 00:00:00 2001 From: Barduino Date: Thu, 30 Jul 2015 15:04:58 -0400 Subject: [PATCH 134/137] Delete MockMySensors --- libraries/MySensors/examples/MockMySensors | 1018 -------------------- 1 file changed, 1018 deletions(-) delete mode 100644 libraries/MySensors/examples/MockMySensors diff --git a/libraries/MySensors/examples/MockMySensors b/libraries/MySensors/examples/MockMySensors deleted file mode 100644 index 4397208..0000000 --- a/libraries/MySensors/examples/MockMySensors +++ /dev/null @@ -1,1018 +0,0 @@ -/* -* FakeMySensors -* -* This skecth is intended to crate fake sensors which register and respond to the controller -* -* Barduino 2015 -*/ - -#include -#include - -// SPI Pins -#define CE_PIN 9 -#define CS_PIN 10 - -// Wait times -#define LONG_WAIT 500 -#define SHORT_WAIT 50 - -#define SKETCH_NAME "FakeMySensors " -#define SKETCH_VERSION "v0.2" - -// Define Sensors ids -/* S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, - S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, - S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, - S_SCENE_CONTROLLER -*/ - -////#define ID_S_ARDUINO_NODE //auto defined in initialization -////#define ID_S_ARDUINO_REPEATER_NODE //auto defined in initialization - -//#define ID_S_DOOR 1 -//#define ID_S_MOTION 2 -//#define ID_S_SMOKE 3 -//#define ID_S_LIGHT 4 -//#define ID_S_DIMMER 5 -//#define ID_S_COVER 6 -//#define ID_S_TEMP 7 -//#define ID_S_HUM 8 -//#define ID_S_BARO 9 -//#define ID_S_WIND 10 -//#define ID_S_RAIN 11 -//#define ID_S_UV 12 -//#define ID_S_WEIGHT 13 -#define ID_S_POWER 14 -#define ID_S_HEATER 15 -#define ID_S_DISTANCE 16 -#define ID_S_LIGHT_LEVEL 17 -#define ID_S_LOCK 18 -#define ID_S_IR 19 -#define ID_S_WATER 20 -#define ID_S_AIR_QUALITY 21 -#define ID_S_DUST 22 -#define ID_S_SCENE_CONTROLLER 23 - -#define ID_S_CUSTOM 24 - -// Global Vars -unsigned long SLEEP_TIME = 60000; // Sleep time between reads (in milliseconds) -boolean metric = true; -long randNumber; - -// Instanciate MySersors Gateway -MySensor gw(CE_PIN,CS_PIN); - -//Instanciate Messages objects - -#ifdef ID_S_DOOR - MyMessage msg_S_DOOR(ID_S_DOOR,V_TRIPPED); -#endif - -#ifdef ID_S_MOTION - MyMessage msg_S_MOTION_A(ID_S_MOTION,V_ARMED); - MyMessage msg_S_MOTION_T(ID_S_MOTION,V_TRIPPED); -#endif - -#ifdef ID_S_SMOKE - MyMessage msg_S_SMOKE(ID_S_SMOKE,V_TRIPPED); -#endif - -#ifdef ID_S_LIGHT - MyMessage msg_S_LIGHT(ID_S_LIGHT,V_LIGHT); -#endif - -#ifdef ID_S_DIMMER - MyMessage msg_S_DIMMER(ID_S_DIMMER,V_DIMMER); -#endif - -#ifdef ID_S_COVER - MyMessage msg_S_COVER_U(ID_S_COVER,V_UP); - MyMessage msg_S_COVER_D(ID_S_COVER,V_DOWN); - MyMessage msg_S_COVER_S(ID_S_COVER,V_STOP); -#endif - -#ifdef ID_S_TEMP - MyMessage msg_S_TEMP(ID_S_TEMP,V_TEMP); -#endif - -#ifdef ID_S_HUM - MyMessage msg_S_HUM(ID_S_HUM,V_HUM); -#endif - -#ifdef ID_S_BARO - MyMessage msg_S_BARO_P(ID_S_BARO,V_PRESSURE); - MyMessage msg_S_BARO_F(ID_S_BARO,V_FORECAST); -#endif - -#ifdef ID_S_WIND - MyMessage msg_S_WIND_S(ID_S_WIND,V_WIND); - MyMessage msg_S_WIND_G(ID_S_WIND,V_GUST); - MyMessage msg_S_WIND_D(ID_S_WIND,V_DIRECTION); -#endif - -#ifdef ID_S_RAIN - MyMessage msg_S_RAIN_A(ID_S_RAIN,V_RAIN); - MyMessage msg_S_RAIN_R(ID_S_RAIN,V_RAINRATE); -#endif - -#ifdef ID_S_UV - MyMessage msg_S_UV(ID_S_UV,V_UV); -#endif - -#ifdef ID_S_WEIGHT - MyMessage msg_S_WEIGHT(ID_S_WEIGHT,V_WEIGHT); -#endif - -#ifdef ID_S_POWER - MyMessage msg_S_POWER_I(ID_S_POWER,V_IMPEDANCE); - MyMessage msg_S_POWER_W(ID_S_POWER,V_WATT); - MyMessage msg_S_POWER_K(ID_S_POWER,V_KWH); - MyMessage msg_S_POWER_V(ID_S_POWER,V_VOLTAGE); - MyMessage msg_S_POWER_C(ID_S_POWER,V_CURRENT); -#endif - -#ifdef ID_S_HEATER - MyMessage msg_S_HEATER_M(ID_S_HEATER,V_HEATER); - MyMessage msg_S_HEATER_S(ID_S_HEATER,V_HEATER_SW); -#endif - -#ifdef ID_S_DISTANCE - MyMessage msg_S_DISTANCE(ID_S_DISTANCE,V_DISTANCE); -#endif - -#ifdef ID_S_LIGHT_LEVEL - MyMessage msg_S_LIGHT_LEVEL(ID_S_LIGHT_LEVEL,V_LIGHT_LEVEL); -#endif - -#ifdef ID_S_LOCK - MyMessage msg_S_LOCK(ID_S_LOCK,V_LOCK_STATUS); -#endif - -#ifdef ID_S_IR - MyMessage msg_S_IR_S(ID_S_IR,V_IR_SEND); - MyMessage msg_S_IR_R(ID_S_IR,V_IR_RECEIVE); -#endif - -#ifdef ID_S_WATER - MyMessage msg_S_WATER_F(ID_S_WATER,V_FLOW); - MyMessage msg_S_WATER_V(ID_S_WATER,V_VOLUME); -#endif - -#ifdef ID_S_AIR_QUALITY - MyMessage msg_S_AIR_QUALITY(ID_S_AIR_QUALITY,V_VAR1); -#endif - -#ifdef ID_S_DUST - MyMessage msg_S_DUST(ID_S_DUST,V_DUST_LEVEL); -#endif - -#ifdef ID_S_SCENE_CONTROLLER - MyMessage msg_S_SCENE_CONTROLLER_ON(ID_S_SCENE_CONTROLLER,V_SCENE_ON); - MyMessage msg_S_SCENE_CONTROLLER_OF(ID_S_SCENE_CONTROLLER,V_SCENE_OFF); -#endif - -#ifdef ID_S_CUSTOM - MyMessage msg_S_CUSTOM_2(ID_S_CUSTOM,V_VAR2); - MyMessage msg_S_CUSTOM_3(ID_S_CUSTOM,V_VAR3); - MyMessage msg_S_CUSTOM_4(ID_S_CUSTOM,V_VAR4); - MyMessage msg_S_CUSTOM_5(ID_S_CUSTOM,V_VAR5); -#endif - - - - -void setup() -{ - // Random SEED - randomSeed(analogRead(0)); - - // Start the gateway - gw.begin(incomingMessage,254); - gw.wait(LONG_WAIT); - Serial.println("GW Started"); - - // Send the Sketch Version Information to the Gateway - Serial.print("Send Sketch Info: "); - gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION); - Serial.print(SKETCH_NAME); - Serial.println(SKETCH_VERSION); - gw.wait(LONG_WAIT); - - // Get controller configuration - Serial.print("Get Config: "); - metric = gw.getConfig().isMetric; - Serial.println(metric ? "Metric":"Imperial"); - gw.wait(LONG_WAIT); - - // Register all sensors to gw (they will be created as child devices) - Serial.println("Presenting Nodes"); - Serial.println("________________"); - - #ifdef ID_S_DOOR - Serial.println(" S_DOOR"); - gw.present(ID_S_DOOR,S_DOOR); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_MOTION - Serial.println(" S_MOTION"); - gw.present(ID_S_MOTION,S_MOTION); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_SMOKE - Serial.println(" S_SMOKE"); - gw.present(ID_S_SMOKE,S_SMOKE); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_LIGHT - Serial.println(" S_LIGHT"); - gw.present(ID_S_LIGHT,S_LIGHT); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_DIMMER - Serial.println(" S_DIMMER"); - gw.present(ID_S_DIMMER,S_DIMMER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_COVER - Serial.println(" S_COVER"; - gw.present(ID_S_COVER,S_COVER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_TEMP - Serial.println(" S_TMEP"); - gw.present(ID_S_TEMP,S_TEMP); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_HUM - Serial.println(" S_HUM"); - gw.present(ID_S_HUM,S_HUM); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_BARO - Serial.println(" S_BARO"); - gw.present(ID_S_BARO,S_BARO); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_WIND - Serial.println(" S_WIND"); - gw.present(ID_S_WIND,S_WIND); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_RAIN - Serial.println(" S_RAIN"); - gw.present(ID_S_RAIN,S_RAIN); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_UV - Serial.println(" S_UV"); - gw.present(ID_S_UV,S_UV); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_WEIGHT - Serial.println(" S_WEIGHT"): - gw.present(ID_S_WEIGHT,S_WEIGHT); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_POWER - Serial.println(" S_POWER"); - gw.present(ID_S_POWER,S_POWER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_HEATER - Serial.println(" S_HEATER"); - gw.present(ID_S_HEATER,S_HEATER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_DISTANCE - Serial.println(" S_DISTANCE"); - gw.present(ID_S_DISTANCE,S_DISTANCE); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_LIGHT_LEVEL - Serial.println(" S_LIGHT_LEVEL"); - gw.present(ID_S_LIGHT_LEVEL,S_LIGHT_LEVEL); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_LOCK - Serial.println(" S_LOCK"); - gw.present(ID_S_LOCK,S_LOCK); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_IR - Serial.println(" S_IR"); - gw.present(ID_S_IR,S_IR); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_WATER - Serial.println(" S_WATER"); - gw.present(ID_S_WATER,S_WATER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_AIR_QUALITY - Serial.println(" S_AIR_QUALITY"); - gw.present(ID_S_AIR_QUALITY,S_AIR_QUALITY); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_DUST - Serial.println(" S_DUST"); - gw.present(ID_S_DUST,S_DUST); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_SCENE_CONTROLLER - Serial.println(" S_SCENE_CONTROLLER"); - gw.present(ID_S_SCENE_CONTROLLER,S_SCENE_CONTROLLER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_CUSTOM - Serial.println(" S_CUSTOM"); - gw.present(ID_S_CUSTOM,S_CUSTOM); - gw.wait(SHORT_WAIT); - #endif - - - -Serial.println("________________"); - -} - -void loop() -{ - Serial.println(""); - Serial.println(""); - Serial.println(""); - Serial.println("#########################"); - randNumber=random(0,101); - - Serial.print("RandomNumber:"); - Serial.println(randNumber); - // Send fake battery level - Serial.println("Send Battery Level"); - gw.sendBatteryLevel(randNumber); - gw.wait(LONG_WAIT); - - // Request time - Serial.println("Request Time"); - gw.requestTime(receiveTime); - gw.wait(LONG_WAIT); - - //Read Sensors - #ifdef S_ID_DOOR - door(); - #endif - - #ifdef ID_S_MOTION - motion(); - #endif - - #ifdef ID_S_SMOKE - smoke(); - #endif - - #ifdef ID_S_LIGHT - light(); - #endif - - #ifdef ID_S_DIMMER - dimmer(); - #endif - - #ifdef ID_S_COVER - cover(); - #endif - - #ifdef ID_S_TEMP - temp(); - #endif - - #ifdef ID_S_HUM - hum(); - #endif - - #ifdef ID_S_BARO - baro(); - #endif - - #ifdef ID_S_WIND - wind(); - #endif - - #ifdef ID_S_RAIN - rain(); - #endif - - #ifdef ID_S_UV - uv(); - #endif - - #ifdef ID_S_WEIGHT - weight(); - #endif - - #ifdef ID_S_POWER - power(); - #endif - - #ifdef ID_S_HEATER - heater(); - #endif - - #ifdef ID_S_DISTANCE - distance(); - #endif - - #ifdef ID_S_LIGHT_LEVEL - light_level(); - #endif - - #ifdef ID_S_LOCK - lock(); - #endif - - #ifdef ID_S_IR - ir(); - #endif - - #ifdef ID_S_WATER - water(); - #endif - - #ifdef ID_S_AIR_QUALITY - air(); - #endif - - #ifdef ID_S_DUST - dust(); - #endif - - #ifdef ID_S_SCENE_CONTROLLER - scene(); - #endif - - #ifdef ID_S_CUSTOM - custom(); - #endif - - gw.sendBatteryLevel(randNumber); - gw.wait(SHORT_WAIT); - gw.process(); - Serial.println("#########################"); - gw.wait(SLEEP_TIME); //sleep a bit -} - -// This is called when a new time value was received -void receiveTime(unsigned long controllerTime) { - - Serial.print("Time value received: "); - Serial.println(controllerTime); - -} - -//void door(){} - -#ifdef S_ID_DOOR -void door(){ - - Serial.print("Door is: " ); - - if (randNumber <= 50) { - Serial.println("Open"); - gw.send(msg_S_DOOR.set(1)); - } else { - Serial.println("Closed"); - gw.send(msg_S_DOOR.set(0)); - } - -} -#endif - -#ifdef ID_S_MOTION -void motion(){ - - Serial.print("Motion is: " ); - - if (randNumber <= 50) { - Serial.println("Active"); - gw.send(msg_S_MOTION_T.set(1)); - } else { - Serial.println("Quiet"); - gw.send(msg_S_MOTION_T.set(0)); - } - -} -#endif - -#ifdef ID_S_SMOKE -void smoke(){ - - Serial.print("Smoke is: " ); - - if (randNumber <= 50) { - Serial.println("Active"); - gw.send(msg_S_SMOKE.set(1)); - } else { - Serial.println("Quiet"); - gw.send(msg_S_SMOKE.set(0)); - } - -} -#endif - -#ifdef ID_S_LIGHT -void light(){ - - bool isLightOn = gw.loadState(ID_S_LIGHT); - - Serial.print("Light is: " ); - - if (isLightOn) { - Serial.println("On"); - gw.send(msg_S_LIGHT.set(1)); - } else { - Serial.println("Off"); - gw.send(msg_S_LIGHT.set(0)); - } - -} -#endif - -#ifdef ID_S_DIMMER -void dimmer(){ - - int dimmerVal = gw.loadState(ID_S_DIMMER); - - Serial.print("Dimmer is set to: " ); - Serial.println(dimmerVal); - - gw.send(msg_S_DIMMER.set(dimmerVal)); - -} -#endif - -#ifdef ID_S_COVER -void cover(){ - - int coverVal = gw.loadState(ID_S_COVER); - - Serial.print("Cover is : " ); - - switch (coverVal) { - case 0: - Serial.println("Opening"); - gw.send(msg_S_COVER_U.set(V_UP)); - break; - case 1: - Serial.println("Closing"); - gw.send(msg_S_COVER_D.set(V_DOWN)); - break; - default: - Serial.println("Idle"); - gw.send(msg_S_COVER_S.set(V_STOP)); - } - -} -#endif - -#ifdef ID_S_TEMP -void temp(){ - - Serial.print("Temperature is: " ); - Serial.println(map(randNumber,1,100,0,45)); - - gw.send(msg_S_TEMP.set(map(randNumber,1,100,0,45))); - -} -#endif - -#ifdef ID_S_HUM -void hum(){ - - Serial.print("Humitidty is: " ); - Serial.println(randNumber); - - gw.send(msg_S_HUM.set(randNumber)); - -} -#endif - -#ifdef ID_S_BARO -void baro(){ - - const char *weather[] = {"stable","sunny","cloudy","unstable","thunderstorm","unknown"}; - long pressure = map(randNumber,1,100,87000,108600); - int forecast = map(randNumber,1,100,0,5); - - Serial.print("Atmosferic Pressure is: " ); - Serial.println(pressure); - gw.send(msg_S_BARO_P.set(pressure)); - - Serial.print("Weather forecast: " ); - Serial.println(weather[forecast]); - gw.send(msg_S_BARO_F.set(weather[forecast])); - -} -#endif - -#ifdef ID_S_WIND -void wind(){ - - Serial.print("Wind Speed is: " ); - Serial.println(randNumber); - gw.send(msg_S_WIND_S.set(randNumber)); - - Serial.print("Wind Gust is: " ); - Serial.println(randNumber+10); - gw.send(msg_S_WIND_G.set(randNumber+10)); - - Serial.print("Wind Direction is: " ); - Serial.println(map(randNumber,1,100,0,360)); - gw.send(msg_S_WIND_D.set(map(randNumber,1,100,0,360))); - -} -#endif - -#ifdef ID_S_RAIN -void rain(){ - - Serial.print("Rain ammount is: " ); - Serial.println(randNumber); - - gw.send(msg_S_RAIN_A.set(randNumber)); - - Serial.print("Rain rate is: " ); - Serial.println(randNumber/60); - - gw.send(msg_S_RAIN_R.set(randNumber/60,1)); - -} -#endif - -#ifdef ID_S_UV -void uv(){ - - Serial.print("Ultra Violet level is: " ); - Serial.println(map(randNumber,1,100,0,15)); - - gw.send(msg_S_UV.set(map(randNumber,1,100,0,15))); - -} -#endif - -#ifdef ID_S_WEIGHT -void weight(){ - - Serial.print("Weight is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_WEIGHT.set(map(randNumber,1,100,0,150))); - -} -#endif - -#ifdef ID_S_POWER -void power(){ - - Serial.print("Impedance is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_POWER_I.set(map(randNumber,1,100,0,150))); - - Serial.print("Watt is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_POWER_W.set(map(randNumber,1,100,0,150))); - - Serial.print("KWH is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_POWER_K.set(map(randNumber,1,100,0,150))); - - Serial.print("Voltage is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_POWER_V.set(map(randNumber,1,100,0,150))); - - Serial.print("Current is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_POWER_C.set(map(randNumber,1,100,0,150))); - -} -#endif - -#ifdef ID_S_HEATER -void heater(){ - int heater_mode = gw.loadState(ID_S_HEATER); - bool heater_switch = gw.loadState(ID_S_HEATER+1); - - Serial.print("Heater mode is: " ); - - if (heater_mode == 0){ - Serial.println("Off"); - } - else if (heater_mode == 1){ - Serial.println("Heat On"); - } - else if (heater_mode == 2){ - Serial.println("Cool On"); - } - else if (heater_mode == 3){ - Serial.println("Auto Change Over"); - } - else { - Serial.print("Unknown Heater Mode: "); - Serial.println(heater_mode); - } - - gw.send(msg_S_HEATER_M.set(heater_mode)); - - Serial.print("Heater is: " ); - Serial.println(heater_switch?"On":"Off"); - - gw.send(msg_S_HEATER_S.set(heater_switch)); - -} -#endif - -#ifdef ID_S_DISTANCE -void distance(){ - - Serial.print("Distance is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_DISTANCE.set(map(randNumber,1,100,0,150))); - -} -#endif - -#ifdef ID_S_LIGHT_LEVEL -void light_level(){ - - Serial.print("Light is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_LIGHT_LEVEL.set(map(randNumber,1,100,0,150))); - -} -#endif - -#ifdef ID_S_LOCK -void lock(){ - - bool isLocked = gw.loadState(ID_S_LOCK); - - Serial.print("Lock is: " ); - - if (isLocked) { - Serial.println("On"); - gw.send(msg_S_LOCK.set(1)); - } else { - Serial.println("Off"); - gw.send(msg_S_LOCK.set(0)); - } - -} -#endif - -#ifdef ID_S_IR -void ir(){ - - int irVal = gw.loadState(ID_S_IR); - - Serial.print("Infrared is: " ); - Serial.println(irVal); - - gw.send(msg_S_IR_S.set(irVal)); - -} -#endif - -#ifdef ID_S_WATER -void water(){ - - Serial.print("Water flow is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_WATER_F.set(map(randNumber,1,100,0,150))); - - Serial.print("Water volume is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_WATER_V.set(map(randNumber,1,100,0,150))); - -} -#endif - -#ifdef ID_S_AIR_QUALITY -void air(){ - - Serial.print("Air Quality is: " ); - Serial.println(randNumber); - - gw.send(msg_S_AIR_QUALITY.set(randNumber)); - -} -#endif - -#ifdef ID_S_DUST -void dust(){ - - Serial.print("Dust level is: " ); - Serial.println(randNumber); - - gw.send(msg_S_DUST.set(randNumber)); - -} -#endif - -#ifdef ID_S_SCENE_CONTROLLER -void scene(){ - - bool isSceneOn = gw.loadState(ID_S_SCENE_CONTROLLER); - - Serial.print("Scene is: " ); - Serial.println(isSceneOn ? "On":"Off"); - - if(isSceneOn) - gw.send(msg_S_SCENE_CONTROLLER_ON.set(isSceneOn)); - else - gw.send(msg_S_SCENE_CONTROLLER_OF.set(isSceneOn)); - -} -#endif - -#ifdef ID_S_CUSTOM -void custom(){ - - Serial.print("Custom value is: " ); - Serial.println(randNumber); - - gw.send(msg_S_CUSTOM_2.set(randNumber)); - gw.send(msg_S_CUSTOM_3.set(randNumber)); - gw.send(msg_S_CUSTOM_4.set(randNumber)); - gw.send(msg_S_CUSTOM_5.set(randNumber)); - -} -#endif - - -void incomingMessage(const MyMessage &message) { - switch (message.type) { - #ifdef ID_S_LIGHT - case V_LIGHT: - gw.saveState(ID_S_LIGHT, message.getBool()); - Serial.print("Incoming change for ID_S_LIGHT:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println(message.getBool()); - break; - #endif - - #ifdef ID_S_DIMMER - case V_DIMMER: - if ((message.getInt()<0)||(message.getInt()>100)) { - Serial.println( "V_DIMMER data invalid (should be 0..100)" ); - break; - } - gw.saveState(ID_S_DIMMER, message.getInt()); - Serial.print("Incoming change for ID_S_DIMMER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println(message.getInt()); - break; - #endif - - #ifdef ID_S_COVER - case V_UP: - gw.saveState(ID_S_COVER, 0); - Serial.print("Incoming change for ID_S_COVER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println("V_UP"); - break; - - case V_DOWN: - gw.saveState(ID_S_COVER, 1); - Serial.print("Incoming change for ID_S_COVER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println("V_DOWN"); - break; - - case V_STOP: - gw.saveState(ID_S_COVER, 2); - Serial.print("Incoming change for ID_S_COVER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println("V_STOP"); - break; - #endif - - #ifdef ID_S_HEATER - case V_HEATER: - gw.saveState(ID_S_HEATER, message.getInt()); - Serial.print("Incoming change for ID_S_HEATER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - - if (message.getInt() == 0){ - Serial.println("Off"); - } - else if (message.getInt() == 1){ - Serial.println("Heat On"); - } - else if (message.getInt() == 2){ - Serial.println("Cool On"); - } - else if (message.getInt() == 3){ - Serial.println("Auto Change Over"); - } - else { - Serial.print("Unknown Heater Mode: "); - Serial.println(message.getInt()); - } - break; - - case V_HEATER_SW: - gw.saveState(ID_S_HEATER+1, message.getBool()); - Serial.print("Incoming change for ID_S_HEATER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println((message.getBool() ? "On":"Off")); - break; - #endif - - #ifdef ID_S_LOCK - case V_LOCK_STATUS: - gw.saveState(ID_S_LOCK, message.getBool()); - Serial.print("Incoming change for ID_S_LOCK:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println(message.getBool()?"Locked":"Unlocked"); - break; - #endif - - #ifdef ID_S_IR - case V_IR_RECEIVE: - gw.saveState(ID_S_IR, message.getInt()); - Serial.print("Incoming change for ID_S_IR:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println(message.getInt()); - break; - #endif - - #ifdef ID_S_SCENE_CONTROLLER - case V_SCENE_ON: - gw.saveState(ID_S_SCENE_CONTROLLER, 1); - Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println("On"); - break; - case V_SCENE_OFF: - gw.saveState(ID_S_SCENE_CONTROLLER, 0); - Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println("Off"); - break; - #endif - - default: - Serial.print("Unknown/UnImplemented message type:"); - Serial.println(message.type); - } - -} - - - - - - - From a89469ebc8997cbca1a6d33c213dc54c1c24c1fd Mon Sep 17 00:00:00 2001 From: Barduino Date: Thu, 30 Jul 2015 15:17:53 -0400 Subject: [PATCH 135/137] Create MockMySensors.ino # FakeMySensors Arduino sketch to fake sensor for the MySensors Library This skecth is intended to crate fake sensors which register and respond to the controller Barduino 2015 ----------------- Comment/Uncomment the sensors you would like to test Arduino Uno R3 can support about 12 sensors before it runs out of memory. You probably need to turn of the MySensor Lib debug to save some memory Nest step will be to remove the read/write to the eprom and extend to support the v1.5 sensors --- .../examples/MockMySensors/MockMySensors.ino | 1018 +++++++++++++++++ 1 file changed, 1018 insertions(+) create mode 100644 libraries/MySensors/examples/MockMySensors/MockMySensors.ino diff --git a/libraries/MySensors/examples/MockMySensors/MockMySensors.ino b/libraries/MySensors/examples/MockMySensors/MockMySensors.ino new file mode 100644 index 0000000..4397208 --- /dev/null +++ b/libraries/MySensors/examples/MockMySensors/MockMySensors.ino @@ -0,0 +1,1018 @@ +/* +* FakeMySensors +* +* This skecth is intended to crate fake sensors which register and respond to the controller +* +* Barduino 2015 +*/ + +#include +#include + +// SPI Pins +#define CE_PIN 9 +#define CS_PIN 10 + +// Wait times +#define LONG_WAIT 500 +#define SHORT_WAIT 50 + +#define SKETCH_NAME "FakeMySensors " +#define SKETCH_VERSION "v0.2" + +// Define Sensors ids +/* S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, + S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, + S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, + S_SCENE_CONTROLLER +*/ + +////#define ID_S_ARDUINO_NODE //auto defined in initialization +////#define ID_S_ARDUINO_REPEATER_NODE //auto defined in initialization + +//#define ID_S_DOOR 1 +//#define ID_S_MOTION 2 +//#define ID_S_SMOKE 3 +//#define ID_S_LIGHT 4 +//#define ID_S_DIMMER 5 +//#define ID_S_COVER 6 +//#define ID_S_TEMP 7 +//#define ID_S_HUM 8 +//#define ID_S_BARO 9 +//#define ID_S_WIND 10 +//#define ID_S_RAIN 11 +//#define ID_S_UV 12 +//#define ID_S_WEIGHT 13 +#define ID_S_POWER 14 +#define ID_S_HEATER 15 +#define ID_S_DISTANCE 16 +#define ID_S_LIGHT_LEVEL 17 +#define ID_S_LOCK 18 +#define ID_S_IR 19 +#define ID_S_WATER 20 +#define ID_S_AIR_QUALITY 21 +#define ID_S_DUST 22 +#define ID_S_SCENE_CONTROLLER 23 + +#define ID_S_CUSTOM 24 + +// Global Vars +unsigned long SLEEP_TIME = 60000; // Sleep time between reads (in milliseconds) +boolean metric = true; +long randNumber; + +// Instanciate MySersors Gateway +MySensor gw(CE_PIN,CS_PIN); + +//Instanciate Messages objects + +#ifdef ID_S_DOOR + MyMessage msg_S_DOOR(ID_S_DOOR,V_TRIPPED); +#endif + +#ifdef ID_S_MOTION + MyMessage msg_S_MOTION_A(ID_S_MOTION,V_ARMED); + MyMessage msg_S_MOTION_T(ID_S_MOTION,V_TRIPPED); +#endif + +#ifdef ID_S_SMOKE + MyMessage msg_S_SMOKE(ID_S_SMOKE,V_TRIPPED); +#endif + +#ifdef ID_S_LIGHT + MyMessage msg_S_LIGHT(ID_S_LIGHT,V_LIGHT); +#endif + +#ifdef ID_S_DIMMER + MyMessage msg_S_DIMMER(ID_S_DIMMER,V_DIMMER); +#endif + +#ifdef ID_S_COVER + MyMessage msg_S_COVER_U(ID_S_COVER,V_UP); + MyMessage msg_S_COVER_D(ID_S_COVER,V_DOWN); + MyMessage msg_S_COVER_S(ID_S_COVER,V_STOP); +#endif + +#ifdef ID_S_TEMP + MyMessage msg_S_TEMP(ID_S_TEMP,V_TEMP); +#endif + +#ifdef ID_S_HUM + MyMessage msg_S_HUM(ID_S_HUM,V_HUM); +#endif + +#ifdef ID_S_BARO + MyMessage msg_S_BARO_P(ID_S_BARO,V_PRESSURE); + MyMessage msg_S_BARO_F(ID_S_BARO,V_FORECAST); +#endif + +#ifdef ID_S_WIND + MyMessage msg_S_WIND_S(ID_S_WIND,V_WIND); + MyMessage msg_S_WIND_G(ID_S_WIND,V_GUST); + MyMessage msg_S_WIND_D(ID_S_WIND,V_DIRECTION); +#endif + +#ifdef ID_S_RAIN + MyMessage msg_S_RAIN_A(ID_S_RAIN,V_RAIN); + MyMessage msg_S_RAIN_R(ID_S_RAIN,V_RAINRATE); +#endif + +#ifdef ID_S_UV + MyMessage msg_S_UV(ID_S_UV,V_UV); +#endif + +#ifdef ID_S_WEIGHT + MyMessage msg_S_WEIGHT(ID_S_WEIGHT,V_WEIGHT); +#endif + +#ifdef ID_S_POWER + MyMessage msg_S_POWER_I(ID_S_POWER,V_IMPEDANCE); + MyMessage msg_S_POWER_W(ID_S_POWER,V_WATT); + MyMessage msg_S_POWER_K(ID_S_POWER,V_KWH); + MyMessage msg_S_POWER_V(ID_S_POWER,V_VOLTAGE); + MyMessage msg_S_POWER_C(ID_S_POWER,V_CURRENT); +#endif + +#ifdef ID_S_HEATER + MyMessage msg_S_HEATER_M(ID_S_HEATER,V_HEATER); + MyMessage msg_S_HEATER_S(ID_S_HEATER,V_HEATER_SW); +#endif + +#ifdef ID_S_DISTANCE + MyMessage msg_S_DISTANCE(ID_S_DISTANCE,V_DISTANCE); +#endif + +#ifdef ID_S_LIGHT_LEVEL + MyMessage msg_S_LIGHT_LEVEL(ID_S_LIGHT_LEVEL,V_LIGHT_LEVEL); +#endif + +#ifdef ID_S_LOCK + MyMessage msg_S_LOCK(ID_S_LOCK,V_LOCK_STATUS); +#endif + +#ifdef ID_S_IR + MyMessage msg_S_IR_S(ID_S_IR,V_IR_SEND); + MyMessage msg_S_IR_R(ID_S_IR,V_IR_RECEIVE); +#endif + +#ifdef ID_S_WATER + MyMessage msg_S_WATER_F(ID_S_WATER,V_FLOW); + MyMessage msg_S_WATER_V(ID_S_WATER,V_VOLUME); +#endif + +#ifdef ID_S_AIR_QUALITY + MyMessage msg_S_AIR_QUALITY(ID_S_AIR_QUALITY,V_VAR1); +#endif + +#ifdef ID_S_DUST + MyMessage msg_S_DUST(ID_S_DUST,V_DUST_LEVEL); +#endif + +#ifdef ID_S_SCENE_CONTROLLER + MyMessage msg_S_SCENE_CONTROLLER_ON(ID_S_SCENE_CONTROLLER,V_SCENE_ON); + MyMessage msg_S_SCENE_CONTROLLER_OF(ID_S_SCENE_CONTROLLER,V_SCENE_OFF); +#endif + +#ifdef ID_S_CUSTOM + MyMessage msg_S_CUSTOM_2(ID_S_CUSTOM,V_VAR2); + MyMessage msg_S_CUSTOM_3(ID_S_CUSTOM,V_VAR3); + MyMessage msg_S_CUSTOM_4(ID_S_CUSTOM,V_VAR4); + MyMessage msg_S_CUSTOM_5(ID_S_CUSTOM,V_VAR5); +#endif + + + + +void setup() +{ + // Random SEED + randomSeed(analogRead(0)); + + // Start the gateway + gw.begin(incomingMessage,254); + gw.wait(LONG_WAIT); + Serial.println("GW Started"); + + // Send the Sketch Version Information to the Gateway + Serial.print("Send Sketch Info: "); + gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION); + Serial.print(SKETCH_NAME); + Serial.println(SKETCH_VERSION); + gw.wait(LONG_WAIT); + + // Get controller configuration + Serial.print("Get Config: "); + metric = gw.getConfig().isMetric; + Serial.println(metric ? "Metric":"Imperial"); + gw.wait(LONG_WAIT); + + // Register all sensors to gw (they will be created as child devices) + Serial.println("Presenting Nodes"); + Serial.println("________________"); + + #ifdef ID_S_DOOR + Serial.println(" S_DOOR"); + gw.present(ID_S_DOOR,S_DOOR); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_MOTION + Serial.println(" S_MOTION"); + gw.present(ID_S_MOTION,S_MOTION); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_SMOKE + Serial.println(" S_SMOKE"); + gw.present(ID_S_SMOKE,S_SMOKE); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LIGHT + Serial.println(" S_LIGHT"); + gw.present(ID_S_LIGHT,S_LIGHT); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DIMMER + Serial.println(" S_DIMMER"); + gw.present(ID_S_DIMMER,S_DIMMER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_COVER + Serial.println(" S_COVER"; + gw.present(ID_S_COVER,S_COVER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_TEMP + Serial.println(" S_TMEP"); + gw.present(ID_S_TEMP,S_TEMP); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_HUM + Serial.println(" S_HUM"); + gw.present(ID_S_HUM,S_HUM); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_BARO + Serial.println(" S_BARO"); + gw.present(ID_S_BARO,S_BARO); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WIND + Serial.println(" S_WIND"); + gw.present(ID_S_WIND,S_WIND); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_RAIN + Serial.println(" S_RAIN"); + gw.present(ID_S_RAIN,S_RAIN); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_UV + Serial.println(" S_UV"); + gw.present(ID_S_UV,S_UV); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WEIGHT + Serial.println(" S_WEIGHT"): + gw.present(ID_S_WEIGHT,S_WEIGHT); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_POWER + Serial.println(" S_POWER"); + gw.present(ID_S_POWER,S_POWER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_HEATER + Serial.println(" S_HEATER"); + gw.present(ID_S_HEATER,S_HEATER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DISTANCE + Serial.println(" S_DISTANCE"); + gw.present(ID_S_DISTANCE,S_DISTANCE); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LIGHT_LEVEL + Serial.println(" S_LIGHT_LEVEL"); + gw.present(ID_S_LIGHT_LEVEL,S_LIGHT_LEVEL); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LOCK + Serial.println(" S_LOCK"); + gw.present(ID_S_LOCK,S_LOCK); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_IR + Serial.println(" S_IR"); + gw.present(ID_S_IR,S_IR); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WATER + Serial.println(" S_WATER"); + gw.present(ID_S_WATER,S_WATER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_AIR_QUALITY + Serial.println(" S_AIR_QUALITY"); + gw.present(ID_S_AIR_QUALITY,S_AIR_QUALITY); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DUST + Serial.println(" S_DUST"); + gw.present(ID_S_DUST,S_DUST); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_SCENE_CONTROLLER + Serial.println(" S_SCENE_CONTROLLER"); + gw.present(ID_S_SCENE_CONTROLLER,S_SCENE_CONTROLLER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_CUSTOM + Serial.println(" S_CUSTOM"); + gw.present(ID_S_CUSTOM,S_CUSTOM); + gw.wait(SHORT_WAIT); + #endif + + + +Serial.println("________________"); + +} + +void loop() +{ + Serial.println(""); + Serial.println(""); + Serial.println(""); + Serial.println("#########################"); + randNumber=random(0,101); + + Serial.print("RandomNumber:"); + Serial.println(randNumber); + // Send fake battery level + Serial.println("Send Battery Level"); + gw.sendBatteryLevel(randNumber); + gw.wait(LONG_WAIT); + + // Request time + Serial.println("Request Time"); + gw.requestTime(receiveTime); + gw.wait(LONG_WAIT); + + //Read Sensors + #ifdef S_ID_DOOR + door(); + #endif + + #ifdef ID_S_MOTION + motion(); + #endif + + #ifdef ID_S_SMOKE + smoke(); + #endif + + #ifdef ID_S_LIGHT + light(); + #endif + + #ifdef ID_S_DIMMER + dimmer(); + #endif + + #ifdef ID_S_COVER + cover(); + #endif + + #ifdef ID_S_TEMP + temp(); + #endif + + #ifdef ID_S_HUM + hum(); + #endif + + #ifdef ID_S_BARO + baro(); + #endif + + #ifdef ID_S_WIND + wind(); + #endif + + #ifdef ID_S_RAIN + rain(); + #endif + + #ifdef ID_S_UV + uv(); + #endif + + #ifdef ID_S_WEIGHT + weight(); + #endif + + #ifdef ID_S_POWER + power(); + #endif + + #ifdef ID_S_HEATER + heater(); + #endif + + #ifdef ID_S_DISTANCE + distance(); + #endif + + #ifdef ID_S_LIGHT_LEVEL + light_level(); + #endif + + #ifdef ID_S_LOCK + lock(); + #endif + + #ifdef ID_S_IR + ir(); + #endif + + #ifdef ID_S_WATER + water(); + #endif + + #ifdef ID_S_AIR_QUALITY + air(); + #endif + + #ifdef ID_S_DUST + dust(); + #endif + + #ifdef ID_S_SCENE_CONTROLLER + scene(); + #endif + + #ifdef ID_S_CUSTOM + custom(); + #endif + + gw.sendBatteryLevel(randNumber); + gw.wait(SHORT_WAIT); + gw.process(); + Serial.println("#########################"); + gw.wait(SLEEP_TIME); //sleep a bit +} + +// This is called when a new time value was received +void receiveTime(unsigned long controllerTime) { + + Serial.print("Time value received: "); + Serial.println(controllerTime); + +} + +//void door(){} + +#ifdef S_ID_DOOR +void door(){ + + Serial.print("Door is: " ); + + if (randNumber <= 50) { + Serial.println("Open"); + gw.send(msg_S_DOOR.set(1)); + } else { + Serial.println("Closed"); + gw.send(msg_S_DOOR.set(0)); + } + +} +#endif + +#ifdef ID_S_MOTION +void motion(){ + + Serial.print("Motion is: " ); + + if (randNumber <= 50) { + Serial.println("Active"); + gw.send(msg_S_MOTION_T.set(1)); + } else { + Serial.println("Quiet"); + gw.send(msg_S_MOTION_T.set(0)); + } + +} +#endif + +#ifdef ID_S_SMOKE +void smoke(){ + + Serial.print("Smoke is: " ); + + if (randNumber <= 50) { + Serial.println("Active"); + gw.send(msg_S_SMOKE.set(1)); + } else { + Serial.println("Quiet"); + gw.send(msg_S_SMOKE.set(0)); + } + +} +#endif + +#ifdef ID_S_LIGHT +void light(){ + + bool isLightOn = gw.loadState(ID_S_LIGHT); + + Serial.print("Light is: " ); + + if (isLightOn) { + Serial.println("On"); + gw.send(msg_S_LIGHT.set(1)); + } else { + Serial.println("Off"); + gw.send(msg_S_LIGHT.set(0)); + } + +} +#endif + +#ifdef ID_S_DIMMER +void dimmer(){ + + int dimmerVal = gw.loadState(ID_S_DIMMER); + + Serial.print("Dimmer is set to: " ); + Serial.println(dimmerVal); + + gw.send(msg_S_DIMMER.set(dimmerVal)); + +} +#endif + +#ifdef ID_S_COVER +void cover(){ + + int coverVal = gw.loadState(ID_S_COVER); + + Serial.print("Cover is : " ); + + switch (coverVal) { + case 0: + Serial.println("Opening"); + gw.send(msg_S_COVER_U.set(V_UP)); + break; + case 1: + Serial.println("Closing"); + gw.send(msg_S_COVER_D.set(V_DOWN)); + break; + default: + Serial.println("Idle"); + gw.send(msg_S_COVER_S.set(V_STOP)); + } + +} +#endif + +#ifdef ID_S_TEMP +void temp(){ + + Serial.print("Temperature is: " ); + Serial.println(map(randNumber,1,100,0,45)); + + gw.send(msg_S_TEMP.set(map(randNumber,1,100,0,45))); + +} +#endif + +#ifdef ID_S_HUM +void hum(){ + + Serial.print("Humitidty is: " ); + Serial.println(randNumber); + + gw.send(msg_S_HUM.set(randNumber)); + +} +#endif + +#ifdef ID_S_BARO +void baro(){ + + const char *weather[] = {"stable","sunny","cloudy","unstable","thunderstorm","unknown"}; + long pressure = map(randNumber,1,100,87000,108600); + int forecast = map(randNumber,1,100,0,5); + + Serial.print("Atmosferic Pressure is: " ); + Serial.println(pressure); + gw.send(msg_S_BARO_P.set(pressure)); + + Serial.print("Weather forecast: " ); + Serial.println(weather[forecast]); + gw.send(msg_S_BARO_F.set(weather[forecast])); + +} +#endif + +#ifdef ID_S_WIND +void wind(){ + + Serial.print("Wind Speed is: " ); + Serial.println(randNumber); + gw.send(msg_S_WIND_S.set(randNumber)); + + Serial.print("Wind Gust is: " ); + Serial.println(randNumber+10); + gw.send(msg_S_WIND_G.set(randNumber+10)); + + Serial.print("Wind Direction is: " ); + Serial.println(map(randNumber,1,100,0,360)); + gw.send(msg_S_WIND_D.set(map(randNumber,1,100,0,360))); + +} +#endif + +#ifdef ID_S_RAIN +void rain(){ + + Serial.print("Rain ammount is: " ); + Serial.println(randNumber); + + gw.send(msg_S_RAIN_A.set(randNumber)); + + Serial.print("Rain rate is: " ); + Serial.println(randNumber/60); + + gw.send(msg_S_RAIN_R.set(randNumber/60,1)); + +} +#endif + +#ifdef ID_S_UV +void uv(){ + + Serial.print("Ultra Violet level is: " ); + Serial.println(map(randNumber,1,100,0,15)); + + gw.send(msg_S_UV.set(map(randNumber,1,100,0,15))); + +} +#endif + +#ifdef ID_S_WEIGHT +void weight(){ + + Serial.print("Weight is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WEIGHT.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_POWER +void power(){ + + Serial.print("Impedance is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_I.set(map(randNumber,1,100,0,150))); + + Serial.print("Watt is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_W.set(map(randNumber,1,100,0,150))); + + Serial.print("KWH is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_K.set(map(randNumber,1,100,0,150))); + + Serial.print("Voltage is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_V.set(map(randNumber,1,100,0,150))); + + Serial.print("Current is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_C.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_HEATER +void heater(){ + int heater_mode = gw.loadState(ID_S_HEATER); + bool heater_switch = gw.loadState(ID_S_HEATER+1); + + Serial.print("Heater mode is: " ); + + if (heater_mode == 0){ + Serial.println("Off"); + } + else if (heater_mode == 1){ + Serial.println("Heat On"); + } + else if (heater_mode == 2){ + Serial.println("Cool On"); + } + else if (heater_mode == 3){ + Serial.println("Auto Change Over"); + } + else { + Serial.print("Unknown Heater Mode: "); + Serial.println(heater_mode); + } + + gw.send(msg_S_HEATER_M.set(heater_mode)); + + Serial.print("Heater is: " ); + Serial.println(heater_switch?"On":"Off"); + + gw.send(msg_S_HEATER_S.set(heater_switch)); + +} +#endif + +#ifdef ID_S_DISTANCE +void distance(){ + + Serial.print("Distance is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_DISTANCE.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_LIGHT_LEVEL +void light_level(){ + + Serial.print("Light is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_LIGHT_LEVEL.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_LOCK +void lock(){ + + bool isLocked = gw.loadState(ID_S_LOCK); + + Serial.print("Lock is: " ); + + if (isLocked) { + Serial.println("On"); + gw.send(msg_S_LOCK.set(1)); + } else { + Serial.println("Off"); + gw.send(msg_S_LOCK.set(0)); + } + +} +#endif + +#ifdef ID_S_IR +void ir(){ + + int irVal = gw.loadState(ID_S_IR); + + Serial.print("Infrared is: " ); + Serial.println(irVal); + + gw.send(msg_S_IR_S.set(irVal)); + +} +#endif + +#ifdef ID_S_WATER +void water(){ + + Serial.print("Water flow is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WATER_F.set(map(randNumber,1,100,0,150))); + + Serial.print("Water volume is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WATER_V.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_AIR_QUALITY +void air(){ + + Serial.print("Air Quality is: " ); + Serial.println(randNumber); + + gw.send(msg_S_AIR_QUALITY.set(randNumber)); + +} +#endif + +#ifdef ID_S_DUST +void dust(){ + + Serial.print("Dust level is: " ); + Serial.println(randNumber); + + gw.send(msg_S_DUST.set(randNumber)); + +} +#endif + +#ifdef ID_S_SCENE_CONTROLLER +void scene(){ + + bool isSceneOn = gw.loadState(ID_S_SCENE_CONTROLLER); + + Serial.print("Scene is: " ); + Serial.println(isSceneOn ? "On":"Off"); + + if(isSceneOn) + gw.send(msg_S_SCENE_CONTROLLER_ON.set(isSceneOn)); + else + gw.send(msg_S_SCENE_CONTROLLER_OF.set(isSceneOn)); + +} +#endif + +#ifdef ID_S_CUSTOM +void custom(){ + + Serial.print("Custom value is: " ); + Serial.println(randNumber); + + gw.send(msg_S_CUSTOM_2.set(randNumber)); + gw.send(msg_S_CUSTOM_3.set(randNumber)); + gw.send(msg_S_CUSTOM_4.set(randNumber)); + gw.send(msg_S_CUSTOM_5.set(randNumber)); + +} +#endif + + +void incomingMessage(const MyMessage &message) { + switch (message.type) { + #ifdef ID_S_LIGHT + case V_LIGHT: + gw.saveState(ID_S_LIGHT, message.getBool()); + Serial.print("Incoming change for ID_S_LIGHT:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getBool()); + break; + #endif + + #ifdef ID_S_DIMMER + case V_DIMMER: + if ((message.getInt()<0)||(message.getInt()>100)) { + Serial.println( "V_DIMMER data invalid (should be 0..100)" ); + break; + } + gw.saveState(ID_S_DIMMER, message.getInt()); + Serial.print("Incoming change for ID_S_DIMMER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getInt()); + break; + #endif + + #ifdef ID_S_COVER + case V_UP: + gw.saveState(ID_S_COVER, 0); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_UP"); + break; + + case V_DOWN: + gw.saveState(ID_S_COVER, 1); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_DOWN"); + break; + + case V_STOP: + gw.saveState(ID_S_COVER, 2); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_STOP"); + break; + #endif + + #ifdef ID_S_HEATER + case V_HEATER: + gw.saveState(ID_S_HEATER, message.getInt()); + Serial.print("Incoming change for ID_S_HEATER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + + if (message.getInt() == 0){ + Serial.println("Off"); + } + else if (message.getInt() == 1){ + Serial.println("Heat On"); + } + else if (message.getInt() == 2){ + Serial.println("Cool On"); + } + else if (message.getInt() == 3){ + Serial.println("Auto Change Over"); + } + else { + Serial.print("Unknown Heater Mode: "); + Serial.println(message.getInt()); + } + break; + + case V_HEATER_SW: + gw.saveState(ID_S_HEATER+1, message.getBool()); + Serial.print("Incoming change for ID_S_HEATER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println((message.getBool() ? "On":"Off")); + break; + #endif + + #ifdef ID_S_LOCK + case V_LOCK_STATUS: + gw.saveState(ID_S_LOCK, message.getBool()); + Serial.print("Incoming change for ID_S_LOCK:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getBool()?"Locked":"Unlocked"); + break; + #endif + + #ifdef ID_S_IR + case V_IR_RECEIVE: + gw.saveState(ID_S_IR, message.getInt()); + Serial.print("Incoming change for ID_S_IR:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getInt()); + break; + #endif + + #ifdef ID_S_SCENE_CONTROLLER + case V_SCENE_ON: + gw.saveState(ID_S_SCENE_CONTROLLER, 1); + Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("On"); + break; + case V_SCENE_OFF: + gw.saveState(ID_S_SCENE_CONTROLLER, 0); + Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("Off"); + break; + #endif + + default: + Serial.print("Unknown/UnImplemented message type:"); + Serial.println(message.type); + } + +} + + + + + + + From bb39d1f548c21ca2bcb014487b99a6d9b9337259 Mon Sep 17 00:00:00 2001 From: Barduino Date: Thu, 30 Jul 2015 15:18:13 -0400 Subject: [PATCH 136/137] Create README.md --- .../MySensors/examples/MockMySensors/README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 libraries/MySensors/examples/MockMySensors/README.md diff --git a/libraries/MySensors/examples/MockMySensors/README.md b/libraries/MySensors/examples/MockMySensors/README.md new file mode 100644 index 0000000..8b15212 --- /dev/null +++ b/libraries/MySensors/examples/MockMySensors/README.md @@ -0,0 +1,15 @@ +# FakeMySensors +Arduino sketch to fake sensor for the MySensors Library + +This skecth is intended to crate fake sensors which register and respond to the controller + +Barduino 2015 +----------------- + +Comment/Uncomment the sensors you would like to test + +Arduino Uno R3 can support about 12 sensors before it runs out of memory. +You probably need to turn of the MySensor Lib debug to save some memory + +Nest step will be to remove the read/write to the eprom +and extend to support the v1.5 sensors From 3fed88a3277fda211c9e58ed36279fe200590c86 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 30 Jul 2015 21:38:13 +0200 Subject: [PATCH 137/137] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ebb4f31..b803e58 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Arduino ======= -MySensors Arduino Library v1.4 +MySensors Arduino Library v1.5 Please visit www.mysensors.org for more information