├── 9781484213780.jpg ├── LICENSE.txt ├── README.md ├── Software ├── Chapter2Software │ ├── LightSwarm │ │ ├── LightSwarm.ino │ │ └── README.md │ ├── LightSwarm_Pi │ │ ├── LightSwarm.py │ │ ├── README.md │ │ └── state │ │ │ ├── LS-1.txt │ │ │ ├── LSCommand.txt │ │ │ ├── LSResponse.txt │ │ │ └── LSStatus.txt │ ├── LightSwarm_RasPiConnect │ │ ├── LightSwarm.xml │ │ ├── Local.py │ │ └── README.md │ └── SDL_PI_IOTDataCollector │ │ ├── IOTCollector.py │ │ ├── README.md │ │ ├── SolarPowerESP8266.py │ │ ├── SolarPowerESP8266CurrentGraph.py │ │ ├── SolarPowerESP8266VoltageGraph.py │ │ ├── static │ │ ├── solarcurrentgraph.png │ │ └── solarvoltagegraph.png │ │ └── updateGraphs.py ├── Chapter3Software │ ├── WeatherPi-RasPiConnect │ │ ├── GraphSelect.txt │ │ ├── Local.py │ │ ├── LocalExample.py │ │ ├── Localbackup.py │ │ ├── README.md │ │ ├── ST-1.txt │ │ ├── WeatherPi.xml │ │ └── __init__.py │ ├── WeatherPi │ │ ├── Adafruit_ADS1x15 │ │ │ ├── Adafruit_ADS1x15.py │ │ │ ├── Adafruit_I2C.py │ │ │ ├── ads1x15_ex_comparator.py │ │ │ ├── ads1x15_ex_differential.py │ │ │ └── ads1x15_ex_singleended.py │ │ ├── Adafruit_I2C │ │ │ └── Adafruit_I2C.py │ │ ├── Adafruit_Python_BMP │ │ │ ├── Adafruit_BMP │ │ │ │ ├── BMP085.py │ │ │ │ └── __init__.py │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── examples │ │ │ │ ├── google_spreadsheet.py │ │ │ │ └── simpletest.py │ │ │ ├── ez_setup.py │ │ │ └── setup.py │ │ ├── Adafruit_Python_GPIO │ │ │ ├── Adafruit_GPIO │ │ │ │ ├── FT232H.py │ │ │ │ ├── GPIO.py │ │ │ │ ├── I2C.py │ │ │ │ ├── MCP230xx.py │ │ │ │ ├── PWM.py │ │ │ │ ├── Platform.py │ │ │ │ ├── SPI.py │ │ │ │ └── __init__.py │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── ez_setup.py │ │ │ ├── setup.py │ │ │ └── test │ │ │ │ ├── MockGPIO.py │ │ │ │ ├── test_GPIO.py │ │ │ │ ├── test_I2C.py │ │ │ │ ├── test_PWM.py │ │ │ │ ├── test_Platform.py │ │ │ │ └── test_SPI.py │ │ ├── MySQLFiles │ │ │ └── WeatherPi.sql │ │ ├── README.md │ │ ├── RTC_SDL_DS3231 │ │ │ ├── README.md │ │ │ ├── SDL_DS3231.py │ │ │ └── testSDL_DS3231.py │ │ ├── RaspberryPi-AS3935 │ │ │ ├── .travis.yml │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── RPi_AS3935 │ │ │ │ ├── RPi_AS3935.py │ │ │ │ └── __init__.py │ │ │ ├── demo.py │ │ │ ├── requirements.txt │ │ │ ├── requirements │ │ │ │ ├── base.txt │ │ │ │ ├── flake8.txt │ │ │ │ └── pep8.txt │ │ │ ├── setup.cfg │ │ │ ├── setup.py │ │ │ ├── tests │ │ │ │ ├── conftest.py │ │ │ │ ├── test_disp_lco.py │ │ │ │ ├── test_disturbers.py │ │ │ │ ├── test_indoors.py │ │ │ │ ├── test_min_strikes.py │ │ │ │ └── test_noise_floor.py │ │ │ └── tox.ini │ │ ├── SDL_Pi_FRAM │ │ │ ├── README.md │ │ │ ├── SDL_Pi_FRAM.py │ │ │ └── testSDL_Pi_FRAM.py │ │ ├── WeatherPi.py │ │ ├── conf.py │ │ ├── doAllGraphs.py │ │ ├── graphs │ │ │ ├── BarometerLightningGraph.py │ │ │ ├── PowerCurrentGraph.py │ │ │ ├── PowerVoltageGraph.py │ │ │ ├── TemperatureHumidityGraph.py │ │ │ └── testTemp.py │ │ ├── htu21dflib │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── build.sh │ │ │ ├── dweetio │ │ │ ├── dweetio.c │ │ │ ├── htu21dflib │ │ │ ├── htu21dflib.c │ │ │ ├── htu21dflib.h │ │ │ ├── mqtt │ │ │ └── mqtt.c │ │ ├── pclogging.py │ │ ├── sendemail.py │ │ ├── startserver.sh │ │ ├── state │ │ │ ├── SunAirPlusStats.txt │ │ │ ├── WeatherCommand.txt │ │ │ └── WeatherStats.txt │ │ └── testAM2315.py │ └── WeatherPiSQL │ │ └── WeatherPiStructure.sql ├── Chapter4Software │ ├── BeaconAirPython │ │ ├── BeaconAir.py │ │ ├── README.md │ │ ├── ble │ │ │ ├── bleThread.py │ │ │ ├── blescan.py │ │ │ ├── blescan2.py │ │ │ └── testblescan.py │ │ ├── bubblelog.py │ │ ├── config │ │ │ ├── config.py │ │ │ └── conflocal.py │ │ ├── iBeaconChart.py │ │ ├── lights.py │ │ ├── utils.py │ │ └── webmap.py │ ├── BeaconAirRasPiConnectLocal │ │ ├── .Local.py.swp │ │ ├── BeaconAir.xml │ │ ├── Local.py │ │ ├── Local.pyc │ │ ├── LocalExample.py │ │ ├── LocalExample.pyc │ │ ├── README.md │ │ ├── ST-1.txt │ │ └── __init__.py │ ├── iBeacon-Scanner- │ │ ├── README.md │ │ ├── blescan.py │ │ └── testblescan.py │ └── phue │ │ ├── CHANGELOG.md │ │ ├── LICENSE │ │ ├── README.md │ │ ├── TODO.md │ │ ├── examples │ │ ├── random_colors.py │ │ ├── tk_gui_complex.py │ │ ├── tk_gui_hsb.py │ │ └── tk_gui_simple.py │ │ ├── phue.py │ │ ├── phue.sublime-project │ │ └── setup.py ├── Chapter5Software │ ├── IOTPulse │ │ ├── AllSerialHandling.h │ │ ├── IOTPulse.ino │ │ └── Interrupt.h │ └── pubsubclient │ │ ├── .travis.yml │ │ ├── CHANGES.txt │ │ ├── LICENSE.txt │ │ ├── README.md │ │ ├── examples │ │ ├── mqtt_auth │ │ │ └── mqtt_auth.ino │ │ ├── mqtt_basic │ │ │ └── mqtt_basic.ino │ │ ├── mqtt_esp8266 │ │ │ └── mqtt_esp8266.ino │ │ ├── mqtt_publish_in_callback │ │ │ └── mqtt_publish_in_callback.ino │ │ ├── mqtt_reconnect_nonblocking │ │ │ └── mqtt_reconnect_nonblocking.ino │ │ └── mqtt_stream │ │ │ └── mqtt_stream.ino │ │ ├── keywords.txt │ │ ├── library.properties │ │ ├── src │ │ ├── PubSubClient.cpp │ │ └── PubSubClient.h │ │ └── tests │ │ ├── Makefile │ │ ├── README.md │ │ ├── src │ │ ├── connect_spec.cpp │ │ ├── keepalive_spec.cpp │ │ ├── lib │ │ │ ├── Arduino.h │ │ │ ├── BDDTest.cpp │ │ │ ├── BDDTest.h │ │ │ ├── Buffer.cpp │ │ │ ├── Buffer.h │ │ │ ├── Client.h │ │ │ ├── IPAddress.cpp │ │ │ ├── IPAddress.h │ │ │ ├── ShimClient.cpp │ │ │ ├── ShimClient.h │ │ │ ├── Stream.cpp │ │ │ ├── Stream.h │ │ │ └── trace.h │ │ ├── publish_spec.cpp │ │ ├── receive_spec.cpp │ │ └── subscribe_spec.cpp │ │ ├── testcases │ │ ├── __init__.py │ │ ├── mqtt_basic.py │ │ ├── mqtt_publish_in_callback.py │ │ └── settings.py │ │ └── testsuite.py ├── Chapter6Software │ ├── IOTRFID │ │ ├── IOTRFID.ino │ │ ├── PubSubClient.cpp │ │ ├── PubSubClient.h │ │ ├── Utils.h │ │ ├── seeedRFID.cpp │ │ └── seeedRFID.h │ └── SDL_PI_IOTDataCollector │ │ ├── IOTCollector.py │ │ ├── README.md │ │ ├── SolarPowerESP8266.py │ │ ├── SolarPowerESP8266CurrentGraph.py │ │ ├── SolarPowerESP8266VoltageGraph.py │ │ ├── static │ │ ├── solarcurrentgraph.png │ │ └── solarvoltagegraph.png │ │ └── updateGraphs.py └── Chapter7Software │ ├── AESTest │ ├── AESLib-master │ │ ├── AESLib.c │ │ ├── AESLib.h │ │ ├── LICENSE │ │ ├── README.md │ │ ├── aes.h │ │ ├── aes128_dec.h │ │ ├── aes128_enc.h │ │ ├── aes192_dec.h │ │ ├── aes192_enc.h │ │ ├── aes256_dec.h │ │ ├── aes256_enc.h │ │ ├── aes_dec-asm_faster.S │ │ ├── aes_dec.h │ │ ├── aes_enc-asm.S │ │ ├── aes_enc.h │ │ ├── aes_invsbox-asm.S │ │ ├── aes_invsbox.h │ │ ├── aes_keyschedule-asm.S │ │ ├── aes_keyschedule.h │ │ ├── aes_sbox-asm.S │ │ ├── aes_sbox.h │ │ ├── aes_types.h │ │ ├── avr-asm-macros.S │ │ ├── bcal-basic.c │ │ ├── bcal-basic.h │ │ ├── bcal-cbc.c │ │ ├── bcal-cbc.h │ │ ├── bcal-cmac.c │ │ ├── bcal-cmac.h │ │ ├── bcal-ofb.c │ │ ├── bcal-ofb.h │ │ ├── bcal_aes128.c │ │ ├── bcal_aes128.h │ │ ├── bcal_aes192.c │ │ ├── bcal_aes192.h │ │ ├── bcal_aes256.c │ │ ├── bcal_aes256.h │ │ ├── blockcipher_descriptor.h │ │ ├── gf256mul.S │ │ ├── gf256mul.h │ │ ├── keysize_descriptor.c │ │ ├── keysize_descriptor.h │ │ ├── memxor.S │ │ └── memxor.h │ └── AESTest.ino │ ├── Cryptosuite │ ├── README │ └── Sha │ │ ├── examples │ │ ├── hmacsha256test │ │ │ ├── Jamfile │ │ │ ├── hmacsha256test.pde │ │ │ ├── runtests.sh │ │ │ └── test.ex │ │ ├── sha1test │ │ │ └── sha1test.pde │ │ └── sha256test │ │ │ └── sha256test.pde │ │ ├── keywords.txt │ │ ├── readme.txt │ │ ├── sha1.cpp │ │ ├── sha1.h │ │ ├── sha256.cpp │ │ └── sha256.h │ └── sha256test │ ├── sha256.cpp │ ├── sha256.h │ └── sha256test.ino └── contributing.md /9781484213780.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/9781484213780.jpg -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/LICENSE.txt -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Raspberry Pi IoT Projects*](http://www.apress.com/9781484213780) by John C. Shovic (Apress, 2016). 4 | 5 | [comment]: #cover 6 | ![Cover image](9781484213780.jpg) 7 | 8 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 9 | 10 | ## Releases 11 | 12 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 13 | 14 | ## Contributions 15 | 16 | See the file Contributing.md for more information on how you can contribute to this repository. 17 | -------------------------------------------------------------------------------- /Software/Chapter2Software/LightSwarm/README.md: -------------------------------------------------------------------------------- 1 | IOT LightSwarm Self Organizing System 2 | 3 | SwitchDoc Labs, 2016 4 | 5 | For forthcoming IOT projects book from APress. 6 | 7 | -------------------------------------------------------------------------------- /Software/Chapter2Software/LightSwarm_Pi/README.md: -------------------------------------------------------------------------------- 1 | Raspberry Pi Python Code for LightSwarm Logging 2 | 3 | From a forthcoming book on IOT Projects from APress 4 | 5 | SwitchDoc Labs, 2016 6 | -------------------------------------------------------------------------------- /Software/Chapter2Software/LightSwarm_Pi/state/LS-1.txt: -------------------------------------------------------------------------------- 1 | 2.87 -------------------------------------------------------------------------------- /Software/Chapter2Software/LightSwarm_Pi/state/LSCommand.txt: -------------------------------------------------------------------------------- 1 | DONE -------------------------------------------------------------------------------- /Software/Chapter2Software/LightSwarm_Pi/state/LSResponse.txt: -------------------------------------------------------------------------------- 1 | 0,1,28,2872,PR,125 | 1,0,28,357,PR,123 | 2,0,28,248,PR,124 | 3,0,0,0,NP,0 | 4,0,0,0,NP,0 -------------------------------------------------------------------------------- /Software/Chapter2Software/LightSwarm_Pi/state/LSStatus.txt: -------------------------------------------------------------------------------- 1 | 0,1,28,2872,PR,125 | 1,0,28,357,PR,123 | 2,0,28,248,PR,124 | 3,0,0,0,NP,0 | 4,0,0,0,NP,0 -------------------------------------------------------------------------------- /Software/Chapter2Software/LightSwarm_RasPiConnect/README.md: -------------------------------------------------------------------------------- 1 | RaspPiConnect configuration files. See www.milocreek.com/wiki for setup. 2 | 3 | LightSwarm Configutation Files for RasPiConnect - for forthcoming IOT Projects book from APress 4 | 5 | SwitchDoc Labs, 2016 6 | 7 | 8 | -------------------------------------------------------------------------------- /Software/Chapter2Software/SDL_PI_IOTDataCollector/IOTCollector.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # IOT Data Collector 4 | # 5 | # SwitchDoc Labs 6 | # December 2015 7 | # 8 | 9 | import httplib2 as http 10 | import json 11 | 12 | import time 13 | 14 | import SolarPowerESP8266 15 | 16 | 17 | try: 18 | from urlparse import urlparse 19 | except ImportError: 20 | from urllib.parse import urlparse 21 | 22 | # fetch the JSON data from the IOT device 23 | def fetchJSONData(uri, path): 24 | target = urlparse(uri+path) 25 | method = 'GET' 26 | body = '' 27 | 28 | h = http.Http() 29 | 30 | # If you need authentication some example: 31 | #if auth: 32 | # h.add_credentials(auth.user, auth.password) 33 | 34 | response, content = h.request( 35 | target.geturl(), 36 | method, 37 | body, 38 | headers) 39 | 40 | # assume that content is a json reply 41 | # parse content with the json module 42 | data = json.loads(content) 43 | 44 | return data 45 | 46 | headers = { 47 | 'Accept': 'application/json', 48 | 'Content-Type': 'application/json; charset=UTF-8' 49 | } 50 | 51 | # main program 52 | uri = 'http://192.168.1.129' 53 | path = '/' 54 | 55 | 56 | 57 | while True: 58 | 59 | data = fetchJSONData(uri, path) 60 | 61 | if (data['name'] == "SolarPowerESP8266"): 62 | SolarPowerESP8266.parseSolarPowerESP8266(data) 63 | 64 | #print( data['id'], data['name']) 65 | 66 | time.sleep(60.0) 67 | -------------------------------------------------------------------------------- /Software/Chapter2Software/SDL_PI_IOTDataCollector/README.md: -------------------------------------------------------------------------------- 1 | 2 | IOTDataCollector 3 | 4 | SwitchDoc Labs 5 | December 2015 6 | 7 | This code is used for various IOT devices being built by SwitchDoc Labs such as LightSwarm, WeatherPi and SolarPowerESP8266 8 | 9 | Make sure you replace the IP address to match your IOT REST interface 10 | 11 | 12 | -------------------------------------------------------------------------------- /Software/Chapter2Software/SDL_PI_IOTDataCollector/SolarPowerESP8266.py: -------------------------------------------------------------------------------- 1 | # 2 | # SolarPowerESP8266 3 | # 4 | # parsing and storage data 5 | # 6 | # SwitchDoc Labs 7 | # December 2015 8 | # 9 | import time 10 | import datetime 11 | 12 | import MySQLdb as mdb 13 | 14 | def parseSolarPowerESP8266(data): 15 | 16 | type = data["name"] 17 | deviceid = data["id"] 18 | timestamp = data["variables"]["RestTimeStamp"] 19 | dataString = data["variables"]["RestDataString"] 20 | firmwareversion = data["variables"]["FirmwareVersion"] 21 | 22 | ts = time.time() 23 | receivedTimeStamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') 24 | print "%s: sampling SolarPowerESP8266 data" % receivedTimeStamp 25 | 26 | 27 | #print "%s: type= %s deviceid=%s timestamp=%s dataString=%s" % (receivedTimeStamp, type, deviceid, timestamp, dataString) 28 | 29 | 30 | con = mdb.connect('localhost', 'root', 'password', 'IOTSolarData'); 31 | 32 | 33 | # you must create a Cursor object. It will let 34 | # you execute all the queries you need 35 | cur = con.cursor() 36 | 37 | # read all data out of JSON 38 | samples = dataString.split("|") 39 | 40 | if (len(samples) > 1): 41 | # we have data 42 | 43 | print "%i sample(s) read" % (len(samples) -1) 44 | for i in range(len(samples)): 45 | 46 | values = samples[i].split(',') 47 | if (i == 0): 48 | heap_available = int(samples[i]) 49 | else: 50 | sample_timestamp = int(values[0]) 51 | battery_load_voltage = float(values[2]) 52 | battery_current = float(values[3]) 53 | solarcell_load_voltage = float(values[5]) 54 | solarcell_current = float(values[6]) 55 | output_load_voltage = float(values[8]) 56 | output_current = float(values[9]) 57 | 58 | query = 'INSERT INTO SolarPowerData(timestamp,type, deviceid, firmwareversion, heap_available, sample_timestamp, battery_load_voltage, battery_current, solarcell_load_voltage, solarcell_current, output_load_voltage, output_current) VALUES(UTC_TIMESTAMP(), "%s", "%s", "%s", %d, %d, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f)' %( type, deviceid, firmwareversion, heap_available, sample_timestamp, battery_load_voltage, battery_current, solarcell_load_voltage, solarcell_current, output_load_voltage, output_current) 59 | #print("query=%s" % query) 60 | 61 | cur.execute(query) 62 | 63 | con.commit() 64 | -------------------------------------------------------------------------------- /Software/Chapter2Software/SDL_PI_IOTDataCollector/static/solarcurrentgraph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter2Software/SDL_PI_IOTDataCollector/static/solarcurrentgraph.png -------------------------------------------------------------------------------- /Software/Chapter2Software/SDL_PI_IOTDataCollector/static/solarvoltagegraph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter2Software/SDL_PI_IOTDataCollector/static/solarvoltagegraph.png -------------------------------------------------------------------------------- /Software/Chapter2Software/SDL_PI_IOTDataCollector/updateGraphs.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # updates all SolarPowerESP8266 Graphs 4 | # 5 | # SwitchDoc Labs 6 | # December 2015 7 | # 8 | # 9 | import SolarPowerESP8266VoltageGraph 10 | import SolarPowerESP8266CurrentGraph 11 | 12 | 13 | SolarPowerESP8266VoltageGraph.SolarPowerESP8266VoltageGraph("updateGraphs", 10) 14 | SolarPowerESP8266CurrentGraph.SolarPowerESP8266CurrentGraph("updateGraphs", 10) 15 | 16 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi-RasPiConnect/GraphSelect.txt: -------------------------------------------------------------------------------- 1 | system logs -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi-RasPiConnect/LocalExample.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Filename: LocalExample.py 3 | # MiloCreek JS MiloCreek 4 | # Version 2.8 8/12/13 5 | # 6 | # Local Execute Objects for RasPiConnect 7 | # to add Execute objects, modify this file 8 | # 9 | # 10 | # 11 | # RasPiConnectServer interface constants 12 | 13 | REMOTE_WEBVIEW_UITYPE = 1 14 | ACTION_BUTTON_UITYPE = 16 15 | FEEDBACK_ACTION_BUTTON_UITYPE = 17 16 | SINGLE_LED_DISPLAY_UITYPE = 32 17 | SPEEDOMETER_UITYPE = 64 18 | VOLTMETER_UITYPE = 128 19 | BARMETER_UITYPE = 129 20 | SERVER_STATUS_UITYPE = 256 21 | PICTURE_REMOTE_WEBVIEW_UITYPE = 512 22 | LABEL_UITYPE = 1024 23 | FM_BLINK_LED_UITYPE = 2048 24 | TEXT_DISPLAY_UITYPE = 4096 25 | TOGGLE_SWITCH_UITYPE = 33 26 | SEND_TEXT_UITYPE = 34 27 | 28 | # system imports 29 | import sys 30 | import subprocess 31 | 32 | # RasPiConnectImports 33 | 34 | import Config 35 | import Validate 36 | import BuildResponse 37 | 38 | def ExecuteUserObjects(objectType, element): 39 | 40 | # Example Objects 41 | 42 | # fetch information from XML for use in user elements 43 | 44 | #objectServerID is the RasPiConnect ID from the RasPiConnect App 45 | 46 | objectServerID = element.find("./OBJECTSERVERID").text 47 | objectID = element.find("./OBJECTID").text 48 | 49 | if (Config.debug()): 50 | print("objectServerID = %s" % objectServerID) 51 | # 52 | # check to see if this is a Validate request 53 | # 54 | validate = Validate.checkForValidate(element) 55 | 56 | if (Config.debug()): 57 | print "VALIDATE=%s" % validate 58 | 59 | 60 | # Build the header for the response 61 | 62 | outgoingXMLData = BuildResponse.buildHeader(element) 63 | 64 | 65 | # objects are split up by object types by Interface Constants 66 | # 67 | # 68 | # 69 | # search for matches to object Type 70 | 71 | # object Type match 72 | if (objectType == ACTION_BUTTON_UITYPE): 73 | 74 | if (Config.debug()): 75 | print "ACTION_BUTTON_UTYPE of %s found" % objectServerID 76 | 77 | # B-2 - play a beep on the Raspberry Pi 78 | if (objectServerID == "B-2"): 79 | 80 | #check for validate request 81 | # validate allows RasPiConnect to verify this object is here 82 | if (validate == "YES"): 83 | outgoingXMLData += Validate.buildValidateResponse("YES") 84 | outgoingXMLData += BuildResponse.buildFooter() 85 | return outgoingXMLData 86 | 87 | # not validate request, so execute 88 | 89 | # note that python is in the main directory for this call, not the local directory 90 | 91 | output = subprocess.call(["aplay", "sounds/match1.wav"]) 92 | 93 | responseData = "OK" 94 | outgoingXMLData += BuildResponse.buildResponse(responseData) 95 | outgoingXMLData += BuildResponse.buildFooter() 96 | return outgoingXMLData 97 | 98 | 99 | 100 | else: 101 | return "" 102 | # returning a zero length string tells the server that you have not matched 103 | # the object and server 104 | return "" 105 | 106 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi-RasPiConnect/README.md: -------------------------------------------------------------------------------- 1 | # 2 | # Local.py file for RasPiConnect (www.milocreek.com) 3 | # 4 | # SwitchDoc Labs 7/8/2014 5 | # 6 | # copyright GPL2 2014 7 | 8 | WeatherPi.xml is the RasPiConnect file. You can load this from your server into your RasPiConnect App. 9 | 10 | Turn off the XML Configuration File Integrity Check under Settings in RasPiConnect to load this into RasPiConnect! 11 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi-RasPiConnect/ST-1.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter3Software/WeatherPi-RasPiConnect/ST-1.txt -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi-RasPiConnect/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter3Software/WeatherPi-RasPiConnect/__init__.py -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_ADS1x15/Adafruit_I2C.py: -------------------------------------------------------------------------------- 1 | ../Adafruit_I2C/Adafruit_I2C.py -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_ADS1x15/ads1x15_ex_comparator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import time, signal, sys 4 | from Adafruit_ADS1x15 import ADS1x15 5 | 6 | def signal_handler(signal, frame): 7 | print 'You pressed Ctrl+C!' 8 | print adc.getLastConversionResults()/1000.0 9 | adc.stopContinuousConversion() 10 | sys.exit(0) 11 | 12 | signal.signal(signal.SIGINT, signal_handler) 13 | # Print 'Press Ctrl+C to exit' 14 | 15 | ADS1015 = 0x00 # 12-bit ADC 16 | ADS1115 = 0x01 # 16-bit ADC 17 | 18 | # Initialise the ADC using the default mode (use default I2C address) 19 | # Set this to ADS1015 or ADS1115 depending on the ADC you are using! 20 | adc = ADS1x15(ic=ADS1115) 21 | 22 | # start comparator on channel 2 with a thresholdHigh=200mV and low=100mV 23 | # in traditional mode, non-latching, +/-1.024V and 250sps 24 | adc.startSingleEndedComparator(2, 200, 100, pga=1024, sps=250, activeLow=True, traditionalMode=True, latching=False, numReadings=1) 25 | 26 | while True: 27 | print adc.getLastConversionResults()/1000.0 28 | time.sleep(0.25) 29 | 30 | #time.sleep(0.1) 31 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_ADS1x15/ads1x15_ex_differential.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import time, signal, sys 4 | from Adafruit_ADS1x15 import ADS1x15 5 | 6 | def signal_handler(signal, frame): 7 | #print 'You pressed Ctrl+C!' 8 | sys.exit(0) 9 | signal.signal(signal.SIGINT, signal_handler) 10 | #print 'Press Ctrl+C to exit' 11 | 12 | ADS1015 = 0x00 # 12-bit ADC 13 | ADS1115 = 0x01 # 16-bit ADC 14 | 15 | # Initialise the ADC using the default mode (use default I2C address) 16 | # Set this to ADS1015 or ADS1115 depending on the ADC you are using! 17 | adc = ADS1x15(ic=ADS1115) 18 | 19 | # Read channels 2 and 3 in single-ended mode, at +/-4.096V and 250sps 20 | volts2 = adc.readADCSingleEnded(2, 4096, 250)/1000.0 21 | volts3 = adc.readADCSingleEnded(3, 4096, 250)/1000.0 22 | 23 | # Now do a differential reading of channels 2 and 3 24 | voltsdiff = adc.readADCDifferential23(4096, 250)/1000.0 25 | 26 | # Display the two different reading for comparison purposes 27 | print "%.8f %.8f %.8f %.8f" % (volts2, volts3, volts3-volts2, -voltsdiff) 28 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_ADS1x15/ads1x15_ex_singleended.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import time, signal, sys 4 | from Adafruit_ADS1x15 import ADS1x15 5 | 6 | def signal_handler(signal, frame): 7 | print 'You pressed Ctrl+C!' 8 | sys.exit(0) 9 | signal.signal(signal.SIGINT, signal_handler) 10 | #print 'Press Ctrl+C to exit' 11 | 12 | ADS1015 = 0x00 # 12-bit ADC 13 | ADS1115 = 0x01 # 16-bit ADC 14 | 15 | # Select the gain 16 | # gain = 6144 # +/- 6.144V 17 | gain = 4096 # +/- 4.096V 18 | # gain = 2048 # +/- 2.048V 19 | # gain = 1024 # +/- 1.024V 20 | # gain = 512 # +/- 0.512V 21 | # gain = 256 # +/- 0.256V 22 | 23 | # Select the sample rate 24 | # sps = 8 # 8 samples per second 25 | # sps = 16 # 16 samples per second 26 | # sps = 32 # 32 samples per second 27 | # sps = 64 # 64 samples per second 28 | # sps = 128 # 128 samples per second 29 | sps = 250 # 250 samples per second 30 | # sps = 475 # 475 samples per second 31 | # sps = 860 # 860 samples per second 32 | 33 | # Initialise the ADC using the default mode (use default I2C address) 34 | # Set this to ADS1015 or ADS1115 depending on the ADC you are using! 35 | adc = ADS1x15(ic=ADS1115) 36 | 37 | # Read channel 0 in single-ended mode using the settings above 38 | volts = adc.readADCSingleEnded(0, gain, sps) / 1000 39 | 40 | # To read channel 3 in single-ended mode, +/- 1.024V, 860 sps use: 41 | # volts = adc.readADCSingleEnded(3, 1024, 860) 42 | 43 | print "%.6f" % (volts) 44 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_Python_BMP/Adafruit_BMP/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter3Software/WeatherPi/Adafruit_Python_BMP/Adafruit_BMP/__init__.py -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_Python_BMP/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Adafruit Industries 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_Python_BMP/README.md: -------------------------------------------------------------------------------- 1 | Adafruit Python BMP 2 | =================== 3 | 4 | Python library for accessing the BMP series pressure and temperature sensors like the BMP085/BMP180 on a Raspberry Pi or Beaglebone Black. 5 | 6 | Designed specifically to work with the Adafruit BMP085/BMP180 pressure sensors ----> https://www.adafruit.com/products/1603 7 | 8 | To install, download the library by clicking the download zip link to the right and unzip the archive somewhere on your Raspberry Pi or Beaglebone Black. Then execute the following command in the directory of the library: 9 | 10 | ```` 11 | sudo python setup.py install 12 | ```` 13 | 14 | Make sure you have internet access on the device so it can download the required dependencies. 15 | 16 | See examples of usage in the examples folder. 17 | 18 | Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! 19 | 20 | Written by Tony DiCola for Adafruit Industries. 21 | MIT license, all text above must be included in any redistribution 22 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_Python_BMP/examples/simpletest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Copyright (c) 2014 Adafruit Industries 3 | # Author: Tony DiCola 4 | # 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | # 12 | # The above copyright notice and this permission notice shall be included in 13 | # all copies or substantial portions of the Software. 14 | # 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | # THE SOFTWARE. 22 | 23 | # Can enable debug output by uncommenting: 24 | #import logging 25 | #logging.basicConfig(level=logging.DEBUG) 26 | 27 | import Adafruit_BMP.BMP085 as BMP085 28 | 29 | # Default constructor will pick a default I2C bus. 30 | # 31 | # For the Raspberry Pi this means you should hook up to the only exposed I2C bus 32 | # from the main GPIO header and the library will figure out the bus number based 33 | # on the Pi's revision. 34 | # 35 | # For the Beaglebone Black the library will assume bus 1 by default, which is 36 | # exposed with SCL = P9_19 and SDA = P9_20. 37 | sensor = BMP085.BMP085() 38 | 39 | # Optionally you can override the bus number: 40 | #sensor = BMP085.BMP085(busnum=2) 41 | 42 | # You can also optionally change the BMP085 mode to one of BMP085_ULTRALOWPOWER, 43 | # BMP085_STANDARD, BMP085_HIGHRES, or BMP085_ULTRAHIGHRES. See the BMP085 44 | # datasheet for more details on the meanings of each mode (accuracy and power 45 | # consumption are primarily the differences). The default mode is STANDARD. 46 | #sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES) 47 | 48 | print 'Temp = {0:0.2f} *C'.format(sensor.read_temperature()) 49 | print 'Pressure = {0:0.2f} Pa'.format(sensor.read_pressure()) 50 | print 'Altitude = {0:0.2f} m'.format(sensor.read_altitude()) 51 | print 'Sealevel Pressure = {0:0.2f} Pa'.format(sensor.read_sealevel_pressure()) 52 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_Python_BMP/setup.py: -------------------------------------------------------------------------------- 1 | from ez_setup import use_setuptools 2 | use_setuptools() 3 | from setuptools import setup, find_packages 4 | 5 | setup(name = 'Adafruit_BMP', 6 | version = '1.5.0', 7 | author = 'Tony DiCola', 8 | author_email = 'tdicola@adafruit.com', 9 | description = 'Library for accessing the BMP series pressure and temperature sensors like the BMP085/BMP180 on a Raspberry Pi or Beaglebone Black.', 10 | license = 'MIT', 11 | url = 'https://github.com/adafruit/Adafruit_Python_BMP/', 12 | dependency_links = ['https://github.com/adafruit/Adafruit_Python_GPIO/tarball/master#egg=Adafruit-GPIO-0.6.5'], 13 | install_requires = ['Adafruit-GPIO>=0.6.5'], 14 | packages = find_packages()) 15 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_Python_GPIO/Adafruit_GPIO/__init__.py: -------------------------------------------------------------------------------- 1 | from GPIO import * -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_Python_GPIO/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Adafruit Industries 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_Python_GPIO/README.md: -------------------------------------------------------------------------------- 1 | Adafruit Python GPIO Library 2 | ============================ 3 | 4 | Library to provide a cross-platform GPIO interface on the Raspberry Pi and Beaglebone Black using the [RPi.GPIO](https://pypi.python.org/pypi/RPi.GPIO) and [Adafruit_BBIO](https://pypi.python.org/pypi/Adafruit_BBIO) libraries. 5 | 6 | The library is currently in an early stage, but you can see how its used in the [Adafruit Nokia LCD library](https://github.com/adafruit/Adafruit_Nokia_LCD) to write Python code that is easily portable between the Raspberry Pi and Beaglebone Black. 7 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_Python_GPIO/setup.py: -------------------------------------------------------------------------------- 1 | from ez_setup import use_setuptools 2 | use_setuptools() 3 | from setuptools import setup, find_packages 4 | 5 | import sys 6 | 7 | # Define required packages. 8 | requires = [] 9 | # Assume spidev is required on non-windows & non-mac platforms (i.e. linux). 10 | if sys.platform != 'win32' and sys.platform != 'darwin': 11 | requires.append('spidev') 12 | 13 | setup(name = 'Adafruit_GPIO', 14 | version = '0.8.0', 15 | author = 'Tony DiCola', 16 | author_email = 'tdicola@adafruit.com', 17 | description = 'Library to provide a cross-platform GPIO interface on the Raspberry Pi and Beaglebone Black using the RPi.GPIO and Adafruit_BBIO libraries.', 18 | license = 'MIT', 19 | url = 'https://github.com/adafruit/Adafruit_Python_GPIO/', 20 | install_requires = requires, 21 | packages = find_packages()) 22 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/Adafruit_Python_GPIO/test/MockGPIO.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014 Adafruit Industries 2 | # Author: Tony DiCola 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a copy 5 | # of this software and associated documentation files (the "Software"), to deal 6 | # in the Software without restriction, including without limitation the rights 7 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | # copies of the Software, and to permit persons to whom the Software is 9 | # furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | # THE SOFTWARE. 21 | 22 | import Adafruit_GPIO as GPIO 23 | 24 | 25 | class MockGPIO(GPIO.BaseGPIO): 26 | def __init__(self): 27 | self.pin_mode = {} 28 | self.pin_written = {} 29 | self.pin_read = {} 30 | 31 | def setup(self, pin, mode): 32 | self.pin_mode[pin] = mode 33 | 34 | def output(self, pin, bit): 35 | self.pin_written.setdefault(pin, []).append(1 if bit else 0) 36 | 37 | def input(self, pin): 38 | if pin not in self.pin_read: 39 | raise RuntimeError('No mock GPIO data to read for pin {0}'.format(pin)) 40 | return self.pin_read[pin].pop(0) == 1 41 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/MySQLFiles/WeatherPi.sql: -------------------------------------------------------------------------------- 1 | -- phpMyAdmin SQL Dump 2 | -- version 3.4.11.1deb2+deb7u1 3 | -- http://www.phpmyadmin.net 4 | -- 5 | -- Host: localhost 6 | -- Generation Time: May 10, 2015 at 05:31 PM 7 | -- Server version: 5.5.41 8 | -- PHP Version: 5.4.4-14+deb7u12 9 | 10 | SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; 11 | SET time_zone = "+00:00"; 12 | 13 | 14 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 15 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 16 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 17 | /*!40101 SET NAMES utf8 */; 18 | 19 | -- 20 | -- Database: `WeatherPi` 21 | -- 22 | 23 | -- -------------------------------------------------------- 24 | 25 | -- 26 | -- Table structure for table `PowerSystem` 27 | -- 28 | 29 | CREATE TABLE IF NOT EXISTS `PowerSystem` ( 30 | `ID` int(11) NOT NULL AUTO_INCREMENT, 31 | `TimeStamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 32 | `batteryVoltage` float NOT NULL, 33 | `batteryCurrent` float NOT NULL, 34 | `solarVoltage` float NOT NULL, 35 | `solarCurrent` float NOT NULL, 36 | `loadVoltage` float NOT NULL, 37 | `loadCurrent` float NOT NULL, 38 | `batteryPower` float NOT NULL, 39 | `solarPower` float NOT NULL, 40 | `loadPower` float NOT NULL, 41 | `batteryCharge` float NOT NULL, 42 | PRIMARY KEY (`ID`) 43 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6381 ; 44 | 45 | -- -------------------------------------------------------- 46 | 47 | -- 48 | -- Table structure for table `systemlog` 49 | -- 50 | 51 | CREATE TABLE IF NOT EXISTS `systemlog` ( 52 | `ID` int(11) NOT NULL AUTO_INCREMENT, 53 | `TimeStamp` datetime NOT NULL, 54 | `Level` int(11) NOT NULL, 55 | `Source` varchar(250) NOT NULL, 56 | `Message` varchar(250) NOT NULL, 57 | PRIMARY KEY (`ID`) 58 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=295 ; 59 | 60 | -- -------------------------------------------------------- 61 | 62 | -- 63 | -- Table structure for table `WeatherData` 64 | -- 65 | 66 | CREATE TABLE IF NOT EXISTS `WeatherData` ( 67 | `ID` int(20) NOT NULL AUTO_INCREMENT, 68 | `TimeStamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 69 | `as3935LightningCount` float NOT NULL, 70 | `as3935LastInterrupt` float NOT NULL, 71 | `as3935LastDistance` float NOT NULL, 72 | `as3935LastStatus` varchar(200) NOT NULL, 73 | `currentWindSpeed` float NOT NULL, 74 | `currentWindGust` float NOT NULL, 75 | `currentWindDirection` float NOT NULL, 76 | `currentWindDirectionVoltage` float NOT NULL, 77 | `totalRain` float NOT NULL, 78 | `bmp180Temperature` int(20) NOT NULL, 79 | `bmp180Pressure` float NOT NULL, 80 | `bmp180Altitude` float NOT NULL, 81 | `bmp180SeaLevel` float NOT NULL, 82 | `outsideTemperature` float NOT NULL, 83 | `outsideHumidity` float NOT NULL, 84 | `insideTemperature` float NOT NULL, 85 | `insideHumidity` float NOT NULL, 86 | PRIMARY KEY (`ID`) 87 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Weather Data' AUTO_INCREMENT=6019 ; 88 | 89 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 90 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 91 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 92 | 93 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/README.md: -------------------------------------------------------------------------------- 1 | WeatherPi Libraries and Example for Raspberry Pi Solar Powered Weather Station 2 | 3 | Supports SwitchDoc Labs WeatherRack WeatherPiArduino 4 | 5 | Version 1.4 6 | 7 | Other installations required for AM2315: 8 | 9 | sudo apt-get install python-pip 10 | sudo apt-get install libi2c-dev 11 | sudo pip install tentacle_pi 12 | 13 | SwitchDocLabs Documentation for WeatherRack/WeatherPiArduino under products on: 14 | 15 | http://www.switchdoc.com/ 16 | 17 | March 28, 2015 - added subdirectories 18 | May 9, 2015 - Updated software for WatchDog Timer and Email 19 | May 10, 2015 - Added mysql table SQL files for database building 20 | 21 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RTC_SDL_DS3231/README.md: -------------------------------------------------------------------------------- 1 | 2 | Raspberry Pi Python Library for SwitchDoc Labs DS3231/AT24C32 RTC Module 3 | 4 | SwitchDoc Labs, LLC December 19, 2014 5 | 6 | Clone respository and run testDS3231.py to test 7 | 8 | More Information on www.switchdoc.com 9 | 10 | Runs RTC and EEPROM 11 | 12 | 13 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RTC_SDL_DS3231/testSDL_DS3231.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Test SDL_DS3231 4 | # John C. Shovic, SwitchDoc Labs 5 | # 08/03/2014 6 | # 7 | # 8 | 9 | # imports 10 | 11 | import sys 12 | import time 13 | import datetime 14 | import random 15 | import SDL_DS3231 16 | 17 | # Main Program 18 | 19 | print "" 20 | print "Test SDL_DS3231 Version 1.0 - SwitchDoc Labs" 21 | print "" 22 | print "" 23 | print "Program Started at:"+ time.strftime("%Y-%m-%d %H:%M:%S") 24 | print "" 25 | 26 | filename = time.strftime("%Y-%m-%d%H:%M:%SRTCTest") + ".txt" 27 | starttime = datetime.datetime.utcnow() 28 | 29 | ds3231 = SDL_DS3231.SDL_DS3231(1, 0x68) 30 | #comment out the next line after the clock has been initialized 31 | ds3231.write_now() 32 | 33 | # Main Loop - sleeps 10 seconds, then reads and prints values of all clocks 34 | # Also reads two bytes of EEPROM and writes the next value to the two bytes 35 | 36 | # do the AT24C32 eeprom 37 | 38 | print "----------------- " 39 | print "----------------- " 40 | print " Test the AT24C32 EEPROM" 41 | print "----------------- " 42 | print "writing first 10 addresses with random data" 43 | for x in range(0,10): 44 | value = random.randint(0,255) 45 | print "address = %i writing value=%i" % (x, value) 46 | ds3231.write_AT24C32_byte(x, value) 47 | print "----------------- " 48 | 49 | print "reading first 10 addresses" 50 | for x in range(0,10): 51 | print "address = %i value = %i" %(x, ds3231.read_AT24C32_byte(x)) 52 | print "----------------- " 53 | print "----------------- " 54 | 55 | 56 | while True: 57 | 58 | 59 | 60 | 61 | # 62 | currenttime = datetime.datetime.utcnow() 63 | 64 | deltatime = currenttime - starttime 65 | 66 | print "" 67 | print "Raspberry Pi=\t" + time.strftime("%Y-%m-%d %H:%M:%S") 68 | 69 | print "DS3231=\t\t%s" % ds3231.read_datetime() 70 | 71 | print "DS3231 Temp=", ds3231.getTemp() 72 | time.sleep(10.0) 73 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 2.7 3 | env: 4 | - TOX_ENV=pep8 5 | - TOX_ENV=py26 6 | - TOX_ENV=py27 7 | - TOX_ENV=py34 8 | - TOX_ENV=flake8 9 | install: 10 | - pip install --upgrade pip setuptools tox virtualenv . 11 | matrix: 12 | allow_failures: 13 | - env: TOX_ENV=py26 14 | - env: TOX_ENV=py34 15 | script: 16 | - "tox -e $TOX_ENV" 17 | notifications: 18 | email: false 19 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/LICENSE: -------------------------------------------------------------------------------- 1 | Licensed under the Apache License, Version 2.0 (the "License"); 2 | you may not use this file except in compliance with the License. 3 | You may obtain a copy of the License at 4 | 5 | http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/README.md: -------------------------------------------------------------------------------- 1 | RaspberryPi-AS3935 2 | ================== 3 | 4 | [![Build Status](https://travis-ci.org/pcfens/RaspberryPi-AS3935.png?branch=master)](https://travis-ci.org/pcfens/RaspberryPi-AS3935) 5 | 6 | A python library and demo script for interacting with the 7 | [AMS Franklin Lightning Sensor](http://www.ams.com/eng/Products/RF-Products/Lightning-Sensor/AS3935). 8 | 9 | This script will only work if the correct kernel modules are loaded 10 | on your Pi. Adafruit has a nice [tutorial](http://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup/configuring-i2c) 11 | set up, though depending on the breakout board that you use, you may 12 | not see anything show up when you run `i2cdetect`. 13 | 14 | ## Installation 15 | 16 | You can install this module by running 17 | ``` 18 | pip install RPi_AS3935 19 | ``` 20 | 21 | or you can clone this repository and run 22 | ``` 23 | python setup.py install 24 | ``` 25 | 26 | ## Breakout Board 27 | 28 | The AS3935 is a small chip, and rather than trying to solder it myself 29 | I purchased a (v2) breakout board from [Embedded Adventures](http://www.embeddedadventures.com/as3935_lightning_sensor_module_mod-1016.html). 30 | 31 | 32 | ## Connecting the AS3935 33 | 34 | In my test setup I connected my breakout board to the Pi as shown 35 | 36 | | AS3935 Pin | Raspberry Pi Pin | 37 | | ---------: | :--------------- | 38 | | 4 (GND) | 25 (Ground) | 39 | | 5 (VDD) | 1 (3v3 Power) | 40 | | 10 (IRQ) | 11 (GPIO 17) | 41 | | 11 (I2CL) | 5 (SCL) | 42 | | 13 (I2CD) | 3 (SDA) | 43 | 44 | ## Known Issues 45 | 46 | ### Addressing 47 | 48 | You may need edit line 12 of demo.py so that the correct address is read. 49 | 50 | | Breakout Board | Default Address | 51 | | :------------- | :-------------- | 52 | | Embedded Adeventures v2 | 0x00 | 53 | | Embedded Adeventures v4 (untested) | 0x03 | 54 | | Tautic Electronics (untested) | 0x00 | 55 | 56 | ### RaspberryPi Model 57 | 58 | If you have one of the newer 512MB Pi boards, then you need to adjust line 12 59 | in the demo script to read 60 | ```python 61 | sensor = RPi_AS3935(address = 0x00, bus = 1) 62 | ``` 63 | 64 | ## Implementations 65 | 66 | * [Push based web interface](https://github.com/pcfens/RPi-AS3935-Web) 67 | 68 | Send a Pull Request if you'd like to get your original implementation listed here. 69 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/RPi_AS3935/__init__.py: -------------------------------------------------------------------------------- 1 | """A module to make communication between the Raspberry Pi and the 2 | AS3935 lightning sensor (over I2C) as easy as possible. It should be 3 | easily adaptable to make work on non-Raspberry Pi things too. 4 | 5 | .. moduleauthor:: Phil Fenstermacher 6 | 7 | """ 8 | 9 | from RPi_AS3935 import RPi_AS3935 10 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/demo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from RPi_AS3935 import RPi_AS3935 3 | 4 | import RPi.GPIO as GPIO 5 | import time 6 | from datetime import datetime 7 | 8 | GPIO.setmode(GPIO.BCM) 9 | 10 | # Rev. 1 Raspberry Pis should leave bus set at 0, while rev. 2 Pis should set 11 | # bus equal to 1. The address should be changed to match the address of the 12 | # sensor. (Common implementations are in README.md) 13 | sensor = RPi_AS3935(address=0x03, bus=1) 14 | 15 | sensor.set_indoors(True) 16 | sensor.set_noise_floor(0) 17 | sensor.calibrate(tun_cap=0x0F) 18 | 19 | 20 | def handle_interrupt(channel): 21 | time.sleep(0.003) 22 | global sensor 23 | reason = sensor.get_interrupt() 24 | if reason == 0x01: 25 | print "Noise level too high - adjusting" 26 | sensor.raise_noise_floor() 27 | elif reason == 0x04: 28 | print "Disturber detected - masking" 29 | sensor.set_mask_disturber(True) 30 | elif reason == 0x08: 31 | now = datetime.now().strftime('%H:%M:%S - %Y/%m/%d') 32 | distance = sensor.get_distance() 33 | print "We sensed lightning!" 34 | print "It was " + str(distance) + "km away. (%s)" % now 35 | print "" 36 | 37 | pin = 25 38 | 39 | GPIO.setup(pin, GPIO.IN) 40 | GPIO.add_event_detect(pin, GPIO.RISING, callback=handle_interrupt) 41 | 42 | print "Waiting for lightning - or at least something that looks like it" 43 | 44 | while True: 45 | time.sleep(1.0) 46 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/requirements.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | 3 | pytest 4 | coverage 5 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/requirements/base.txt: -------------------------------------------------------------------------------- 1 | RPi_AS3935 >= 0.0.8 2 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/requirements/flake8.txt: -------------------------------------------------------------------------------- 1 | -r base.txt 2 | flake8 3 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/requirements/pep8.txt: -------------------------------------------------------------------------------- 1 | -r base.txt 2 | pep8 3 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | 3 | setup( 4 | name='RPi_AS3935', 5 | version='0.0.9', 6 | description='Raspberry Pi <-I2C-> AS3935 lightning sensor communication library', 7 | author='Phil Fenstermacher', 8 | author_email='phillip.fenstermacher@gmail.com', 9 | url='https://github.com/pcfens/RaspberryPi-AS3935', 10 | packages=['RPi_AS3935'], 11 | keywords=['RaspberryPi', 'AS3935', 'lightning', 'weather'], 12 | license='Apache-2.0', 13 | classifiers=[ 14 | 'Development Status :: 4 - Beta', 15 | 'License :: OSI Approved :: Apache Software License', 16 | 'Topic :: Utilities', 17 | ], 18 | ) 19 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/tests/conftest.py: -------------------------------------------------------------------------------- 1 | from RPi_AS3935 import RPi_AS3935 2 | import pytest 3 | 4 | 5 | class RPi_AS3935Proxy(RPi_AS3935): 6 | def __init__(self, address, bus=0): 7 | self.address = address 8 | self.i2cbus = bus 9 | self.registers = [50, 2, 194, 32, 0, 0, 0, 63, 0, 173, 0, 37, 3, 1, 34, 131, 1, 31, 67, 2, 27, 99, 3, 24, 20, 5, 20, 157, 7, 17, 106, 11] 10 | 11 | def set_byte(self, register, value): 12 | self.registers[register] = value 13 | print value 14 | 15 | def read_data(self): 16 | self.registers = self.registers 17 | 18 | 19 | @pytest.fixture(scope='module') 20 | def as3935(): 21 | return RPi_AS3935Proxy(address=0x00, bus=0) 22 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/tests/test_disp_lco.py: -------------------------------------------------------------------------------- 1 | def test_set_disp_lco_true(as3935): 2 | as3935.set_disp_lco(True) 3 | assert (as3935.registers[0x08] & 0x80) == 0x80 4 | 5 | 6 | def test_get_disp_lco_true(as3935): 7 | disp_lco = as3935.get_disp_lco() 8 | assert disp_lco is True 9 | 10 | 11 | def test_set_disp_lco_false(as3935): 12 | as3935.set_disp_lco(False) 13 | assert (as3935.registers[0x08] & 0x80) == 0x00 14 | 15 | 16 | def test_get_disp_lco_false(as3935): 17 | disp_lco = as3935.get_disp_lco() 18 | assert disp_lco is False 19 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/tests/test_disturbers.py: -------------------------------------------------------------------------------- 1 | def test_set_mask_disturber_true(as3935): 2 | as3935.set_mask_disturber(True) 3 | assert (as3935.registers[0x03] & 0x20) == 0x20 4 | 5 | 6 | def test_get_mask_disturber_true(as3935): 7 | mask_disturber = as3935.get_mask_disturber() 8 | assert mask_disturber is True 9 | 10 | 11 | def test_set_mask_disturber_false(as3935): 12 | as3935.set_mask_disturber(False) 13 | assert (as3935.registers[0x03] & 0x20) == 0x00 14 | 15 | 16 | def test_get_mask_disturber_false(as3935): 17 | mask_disturber = as3935.get_mask_disturber() 18 | assert mask_disturber is False 19 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/tests/test_indoors.py: -------------------------------------------------------------------------------- 1 | def test_set_indoors_true(as3935): 2 | as3935.set_indoors(True) 3 | assert (as3935.registers[0x00] & 0x10) == 0x10 4 | 5 | 6 | def test_get_indoors_true(as3935): 7 | indoors = as3935.get_indoors() 8 | assert indoors is True 9 | 10 | 11 | def test_set_indoors_false(as3935): 12 | as3935.set_indoors(False) 13 | assert (as3935.registers[0x00] & 0x10) == 0x00 14 | 15 | 16 | def test_get_indoors_false(as3935): 17 | indoors = as3935.get_indoors() 18 | assert indoors is False 19 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/tests/test_min_strikes.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | def test_set_min_strikes_5(as3935): 5 | as3935.set_min_strikes(5) 6 | assert (as3935.registers[0x02] & 0x30) == 0x10 7 | 8 | 9 | def test_get_min_strikes_5(as3935): 10 | min_strikes = as3935.get_min_strikes() 11 | assert min_strikes == 5 12 | 13 | 14 | def test_set_invalid_min_strikes(as3935): 15 | with pytest.raises(Exception): 16 | as3935.set_min_strikes(2) 17 | 18 | 19 | def test_set_min_strikes_9(as3935): 20 | as3935.set_min_strikes(9) 21 | assert (as3935.registers[0x02] & 0x30) == 0x20 22 | 23 | 24 | def test_get_min_strikes_9(as3935): 25 | min_strikes = as3935.get_min_strikes() 26 | assert min_strikes == 9 27 | 28 | 29 | def test_set_min_strikes_16(as3935): 30 | as3935.set_min_strikes(16) 31 | assert (as3935.registers[0x02] & 0x30) == 0x30 32 | 33 | 34 | def test_get_min_strikes_16(as3935): 35 | min_strikes = as3935.get_min_strikes() 36 | assert min_strikes == 16 37 | 38 | 39 | def test_set_min_strikes_1(as3935): 40 | as3935.set_min_strikes(1) 41 | assert (as3935.registers[0x02] & 0x30) == 0x00 42 | 43 | 44 | def test_get_min_strikes_1(as3935): 45 | min_strikes = as3935.get_min_strikes() 46 | assert min_strikes == 1 47 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/tests/test_noise_floor.py: -------------------------------------------------------------------------------- 1 | def test_get_noise_floor(as3935): 2 | noise_floor = as3935.get_noise_floor() 3 | assert noise_floor == 0 4 | 5 | 6 | def test_set_noise_floor(as3935): 7 | as3935.set_noise_floor(2) 8 | assert (as3935.registers[0x01] & 0x70) == 0x20 9 | 10 | 11 | def test_raise_noise_floor(as3935): 12 | as3935.raise_noise_floor() 13 | assert (as3935.registers[0x01] & 0x70) == 0x30 14 | 15 | 16 | def test_lower_noise_floor(as3935): 17 | as3935.lower_noise_floor() 18 | assert (as3935.registers[0x01] & 0x70) == 0x20 19 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/RaspberryPi-AS3935/tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = pep8,flake8,py27 3 | 4 | [flake8] 5 | exclude = *.egg*,.env,.git,.hg,.tox,_*,build*,dist*,venv* 6 | ignore = E261 7 | max-line-length = 150 8 | 9 | [pep8] 10 | count = 1 11 | exclude = *.egg*,.env,.git,.hg,.tox,_*,build*,dist*,venv* 12 | ignore = E261 13 | max-line-length = 150 14 | show-source = 1 15 | statistics = 1 16 | 17 | [testenv] 18 | deps = -rrequirements.txt 19 | commands = python -m coverage run --source RPi_AS3935 -m pytest 20 | python -m coverage report -m 21 | 22 | [testenv:pep8] 23 | basepython = python2.7 24 | deps = -rrequirements/pep8.txt 25 | commands = 26 | pep8 tests/ RPi_AS3935/ 27 | 28 | [testenv:flake8] 29 | basepython = python2.7 30 | deps = -rrequirements/flake8.txt 31 | commands = 32 | flake8 tests/ RPi_AS3935/ 33 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/SDL_Pi_FRAM/README.md: -------------------------------------------------------------------------------- 1 | # 2 | # Raspberry Pi I2C FRAM Reading Library 3 | # SwitchDoc Labs 4 | # February 16, 2015 5 | # 6 | # SwitchDoc Labs www.switchdoc.com 7 | # Designed for WeatherPiArduino 8 | # 9 | 10 | 11 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/SDL_Pi_FRAM/SDL_Pi_FRAM.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # SDL_Pi_FRAM.py Python Driver Code 4 | # SwitchDoc Labs 02/16/2014 5 | # V 1.2 6 | 7 | 8 | from datetime import datetime 9 | 10 | import time 11 | import smbus 12 | 13 | 14 | 15 | class SDL_Pi_FRAM(): 16 | 17 | 18 | ########################### 19 | # SDL_Pi_FRAM Code 20 | ########################### 21 | def __init__(self, twi=1, addr=0x50): 22 | self._bus = smbus.SMBus(twi) 23 | self._addr = addr 24 | 25 | 26 | 27 | def write8(self, address, data): 28 | #print "addr =0x%x address = 0x%x data = 0x%x " % (self._addr, address, data) 29 | self._bus.write_i2c_block_data(self._addr,address>>8,[address%256, data]) 30 | 31 | 32 | 33 | def read8(self, address): 34 | 35 | self._bus.write_i2c_block_data(self._addr,address>>8,[address%256]) 36 | returndata = self._bus.read_byte(self._addr) # this will read at the current address pointer, which we on the previous line 37 | #print "addr = 0x%x address = 0x%x %i returndata = 0x%x " % (self._addr, address, address, returndata) 38 | return returndata 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/SDL_Pi_FRAM/testSDL_Pi_FRAM.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Test SDL_Pi_FRAM 4 | # SwitchDoc Labs 5 | # For WeatherPiArduino 6 | # February 16, 2015 7 | # 8 | # 9 | 10 | # imports 11 | 12 | import sys 13 | import time 14 | import random 15 | import SDL_Pi_FRAM 16 | 17 | # Main Program 18 | 19 | print "" 20 | print "Test SDL_Pi_FRAM Version 1.0 - SwitchDoc Labs" 21 | print "" 22 | print "" 23 | print "Program Started at:"+ time.strftime("%Y-%m-%d %H:%M:%S") 24 | print "" 25 | 26 | fram = SDL_Pi_FRAM.SDL_Pi_FRAM(addr = 0x50) 27 | 28 | while True: 29 | print "----------------- " 30 | print "----------------- " 31 | print " Reading and Writing to FRAM " 32 | print "----------------- " 33 | print "writing first 10 addresses with random data" 34 | for x in range(0,10): 35 | value = random.randint(0,255) 36 | print "address = %i writing value=%i" % (x, value) 37 | fram.write8(x, value) 38 | print "----------------- " 39 | 40 | print "reading first 10 addresses" 41 | for x in range(0,10): 42 | print "address = %i value = %i" %(x, fram.read8(x)) 43 | print "----------------- " 44 | print "----------------- " 45 | 46 | time.sleep(10.0) 47 | 48 | 49 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/conf.py: -------------------------------------------------------------------------------- 1 | 2 | # 3 | # 4 | # configuration file - contains customization for exact system 5 | # JCS 11/8/2013 6 | # 7 | 8 | mailUser = "yourusename" 9 | mailPassword = "yourmailpassword" 10 | 11 | notifyAddress ="you@example.com" 12 | 13 | fromAddress = "yourfromaddress@example.com" 14 | 15 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/doAllGraphs.py: -------------------------------------------------------------------------------- 1 | # 2 | # calculate all graphs 3 | # 4 | # SwitchDoc Labs March 30, 2015 5 | 6 | import sys 7 | sys.path.append('/home/pi/WeatherPiSolarPoweredWeather/graphs') 8 | 9 | 10 | 11 | 12 | import TemperatureHumidityGraph 13 | import PowerCurrentGraph 14 | import PowerVoltageGraph 15 | import BarometerLightningGraph 16 | 17 | def doAllGraphs(): 18 | 19 | BarometerLightningGraph.BarometerLightningGraph('test', 10, 0) 20 | TemperatureHumidityGraph.TemperatureHumidityGraph('test', 10, 0) 21 | PowerCurrentGraph.PowerCurrentGraph('test', 10, 0) 22 | PowerVoltageGraph.PowerVoltageGraph('test', 10, 0) 23 | 24 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/graphs/testTemp.py: -------------------------------------------------------------------------------- 1 | 2 | # 3 | # calculate all graphs 4 | # 5 | # SwitchDoc Labs March 30, 2015 6 | 7 | import sys 8 | import RPi.GPIO as GPIO 9 | 10 | 11 | GPIO.setmode(GPIO.BCM) 12 | 13 | 14 | import TemperatureHumidityGraph 15 | 16 | 17 | TemperatureHumidityGraph.TemperatureHumidityGraph('test', 10, 0) 18 | 19 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/htu21dflib/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 bbx10node@gmail.com 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/htu21dflib/README.md: -------------------------------------------------------------------------------- 1 | htu21dflib 2 | ========== 3 | 4 | htu21df temperature and humidity sensor support for Raspberry Pi. 5 | 6 | Adafruit HTU21D-F breakout board details. 7 | 8 | http://www.adafruit.com/products/1899 9 | 10 | Adafruit guide to configuring the Pi for i2c. 11 | 12 | https://learn.adafruit.com/using-the-bmp085-with-raspberry-pi/configuring-the-pi-for-i2c 13 | 14 | ## Build it 15 | 16 | ./build.sh 17 | 18 | ## Run test program 19 | 20 | ./htu21dflib 21 | 22 | Sample output 23 | 24 | ``` 25 | 29.1 52.3 26 | 29.1 52.3 27 | 29.1 52.3 28 | 29.1 52.3 29 | ``` 30 | 31 | ## Dweet your data 32 | 33 | ./dweetio 34 | 35 | Login into http://freeboard.io to access your dweet data. Create a real-time 36 | instrumentation panel with temperature and humidity guages without programming. 37 | 38 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/htu21dflib/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Build the code with a standalone test program. 3 | # htu21dflib -- A small test program using the library. Use it verify 4 | # the code and sensor are working. 5 | # htu21dflib.o -- The library code which can be linked into a larger program. 6 | # dweetio -- Demo program that dweets the data to http://dweet.io. 7 | # Create a real-time instrumentation panel with this data 8 | # by connecting to http://freeboard.io 9 | # 10 | gcc -O2 -Wall -o htu21dflib -DHTU21DFTEST htu21dflib.c 11 | gcc -O2 -Wall -c htu21dflib.c 12 | gcc -O2 -Wall htu21dflib.o -o dweetio dweetio.c 13 | gcc -O2 -Wall htu21dflib.o -o mqtt mqtt.c 14 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/htu21dflib/dweetio: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter3Software/WeatherPi/htu21dflib/dweetio -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/htu21dflib/htu21dflib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter3Software/WeatherPi/htu21dflib/htu21dflib -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/htu21dflib/htu21dflib.h: -------------------------------------------------------------------------------- 1 | /* 2 | The MIT License (MIT) 3 | 4 | Copyright (c) 2014 bbx10 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | */ 24 | 25 | int i2c_open(const char *i2cdevname); 26 | 27 | int i2c_close(int i2cfd); 28 | 29 | int htu21df_init(int i2cfd, uint8_t i2caddr); 30 | 31 | int htu21df_read_temperature(int i2cfd, float *temperature); 32 | 33 | int htu21df_read_humidity(int i2cfd, float *humidity); 34 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/htu21dflib/mqtt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter3Software/WeatherPi/htu21dflib/mqtt -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/pclogging.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # logging system from Project Curacao 4 | # filename: pclogger.py 5 | # Version 1.0 10/04/13 6 | # 7 | # contains logging data 8 | # 9 | 10 | 11 | CRITICAL=50 12 | ERROR=40 13 | WARNING=30 14 | INFO=20 15 | DEBUG=10 16 | NOTSET=0 17 | 18 | 19 | import sys 20 | import time 21 | import MySQLdb as mdb 22 | 23 | DATABASEPASSWORD = "rmysqlpassword" 24 | 25 | def log(level, source, message): 26 | 27 | LOWESTDEBUG = 0 28 | # open mysql database 29 | 30 | # write log 31 | 32 | 33 | # commit 34 | 35 | 36 | # close 37 | 38 | if (level >= LOWESTDEBUG): 39 | try: 40 | 41 | #print("trying database") 42 | con = mdb.connect('localhost', 'root', DATABASEPASSWORD, 'WeatherPi'); 43 | 44 | cur = con.cursor() 45 | #print "before query" 46 | 47 | query = "INSERT INTO systemlog(TimeStamp, Level, Source, Message) VALUES(UTC_TIMESTAMP(), %i, '%s', '%s')" % (level, source, message) 48 | #print("query=%s" % query) 49 | 50 | cur.execute(query) 51 | 52 | con.commit() 53 | 54 | 55 | except mdb.Error, e: 56 | 57 | print "Error %d: %s" % (e.args[0],e.args[1]) 58 | con.rollback() 59 | #sys.exit(1) 60 | 61 | finally: 62 | cur.close() 63 | con.close() 64 | 65 | del cur 66 | del con 67 | 68 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/sendemail.py: -------------------------------------------------------------------------------- 1 | def sendEmail(source, message, subject, toaddress, fromaddress, filename): 2 | 3 | # if conflocal.py is not found, import default conf.py 4 | 5 | # Check for user imports 6 | try: 7 | import conflocal as conf 8 | except ImportError: 9 | import conf 10 | 11 | # Import smtplib for the actual sending function 12 | import smtplib 13 | 14 | # Here are the email package modules we'll need 15 | from email.mime.image import MIMEImage 16 | from email.mime.multipart import MIMEMultipart 17 | from email.mime.text import MIMEText 18 | 19 | COMMASPACE = ', ' 20 | 21 | # Create the container (outer) email message. 22 | msg = MIMEMultipart() 23 | msg['Subject'] = subject 24 | # me == the sender's email address 25 | # family = the list of all recipients' email addresses 26 | msg['From'] = fromaddress 27 | msg['To'] = toaddress 28 | #msg.attach(message) 29 | 30 | mainbody = MIMEText(message, 'plain') 31 | msg.attach(mainbody) 32 | 33 | # Assume we know that the image files are all in PNG format 34 | # Open the files in binary mode. Let the MIMEImage class automatically 35 | # guess the specific image type. 36 | if (filename != ""): 37 | fp = open(filename, 'rb') 38 | img = MIMEImage(fp.read()) 39 | fp.close() 40 | msg.attach(img) 41 | 42 | # Send the email via our own SMTP server. 43 | 44 | try: 45 | # open up a line with the server 46 | s = smtplib.SMTP("smtp.gmail.com", 587) 47 | s.ehlo() 48 | s.starttls() 49 | s.ehlo() 50 | 51 | # login, send email, logout 52 | s.login(conf.mailUser, conf.mailPassword) 53 | s.sendmail(conf.mailUser, toaddress, msg.as_string()) 54 | #s.close() 55 | 56 | 57 | s.quit() 58 | 59 | except: 60 | 61 | print("sendmail exception raised") 62 | return 0 63 | 64 | 65 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/startserver.sh: -------------------------------------------------------------------------------- 1 | 2 | #!/bin/bash 3 | cd /home/pi/WeatherPiSolarPoweredWeather 4 | sudo python WeatherPi.py 5 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/state/SunAirPlusStats.txt: -------------------------------------------------------------------------------- 1 | 3.8884 2 | -236.0 3 | 4.72308 4 | 529.2 5 | 4.928 6 | 216.0 7 | -0.9176624 8 | 2.499453936 9 | 1.064448 10 | 70.9508936451 11 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/state/WeatherCommand.txt: -------------------------------------------------------------------------------- 1 | DONE -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/state/WeatherStats.txt: -------------------------------------------------------------------------------- 1 | 100.298 2 | 0 3 | 0 4 | 0 5 | Noise Floor too low. Adjusting 6 | 3.66246497416 7 | 4.50583054472 8 | 100.298 9 | 46.8 10 | 94 11 | 614.981968619 12 | 94.145 13 | 37.0 14 | 25.2999992371 15 | 135.0 16 | 0.603 17 | 46.7 18 | 53.1 19 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPi/testAM2315.py: -------------------------------------------------------------------------------- 1 | import time 2 | from tentacle_pi.AM2315 import AM2315 3 | am = AM2315(0x5c,"/dev/i2c-1") 4 | 5 | for x in range(0,10): 6 | temperature, humidity, crc_check = am.sense() 7 | print "temperature: %0.1f" % temperature 8 | print "humidity: %0.1f" % humidity 9 | print "crc: %s" % crc_check 10 | print 11 | time.sleep(2.0) 12 | -------------------------------------------------------------------------------- /Software/Chapter3Software/WeatherPiSQL/WeatherPiStructure.sql: -------------------------------------------------------------------------------- 1 | -- phpMyAdmin SQL Dump 2 | -- version 3.4.11.1deb2+deb7u1 3 | -- http://www.phpmyadmin.net 4 | -- 5 | -- Host: localhost 6 | -- Generation Time: Jul 23, 2015 at 12:27 AM 7 | -- Server version: 5.5.44 8 | -- PHP Version: 5.4.41-0+deb7u1 9 | 10 | SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; 11 | SET time_zone = "+00:00"; 12 | 13 | 14 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 15 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 16 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 17 | /*!40101 SET NAMES utf8 */; 18 | 19 | -- 20 | -- Database: `WeatherPi` 21 | -- 22 | 23 | -- -------------------------------------------------------- 24 | 25 | -- 26 | -- Table structure for table `PowerSystem` 27 | -- 28 | 29 | DROP TABLE IF EXISTS `PowerSystem`; 30 | CREATE TABLE IF NOT EXISTS `PowerSystem` ( 31 | `ID` int(11) NOT NULL AUTO_INCREMENT, 32 | `TimeStamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 33 | `batteryVoltage` float NOT NULL, 34 | `batteryCurrent` float NOT NULL, 35 | `solarVoltage` float NOT NULL, 36 | `solarCurrent` float NOT NULL, 37 | `loadVoltage` float NOT NULL, 38 | `loadCurrent` float NOT NULL, 39 | `batteryPower` float NOT NULL, 40 | `solarPower` float NOT NULL, 41 | `loadPower` float NOT NULL, 42 | `batteryCharge` float NOT NULL, 43 | PRIMARY KEY (`ID`) 44 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16170 ; 45 | 46 | -- -------------------------------------------------------- 47 | 48 | -- 49 | -- Table structure for table `systemlog` 50 | -- 51 | 52 | DROP TABLE IF EXISTS `systemlog`; 53 | CREATE TABLE IF NOT EXISTS `systemlog` ( 54 | `ID` int(11) NOT NULL AUTO_INCREMENT, 55 | `TimeStamp` datetime NOT NULL, 56 | `Level` int(11) NOT NULL, 57 | `Source` varchar(250) NOT NULL, 58 | `Message` varchar(250) NOT NULL, 59 | PRIMARY KEY (`ID`) 60 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1527 ; 61 | 62 | -- -------------------------------------------------------- 63 | 64 | -- 65 | -- Table structure for table `WeatherData` 66 | -- 67 | 68 | DROP TABLE IF EXISTS `WeatherData`; 69 | CREATE TABLE IF NOT EXISTS `WeatherData` ( 70 | `ID` int(20) NOT NULL AUTO_INCREMENT, 71 | `TimeStamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 72 | `as3935LightningCount` float NOT NULL, 73 | `as3935LastInterrupt` float NOT NULL, 74 | `as3935LastDistance` float NOT NULL, 75 | `as3935LastStatus` varchar(200) NOT NULL, 76 | `currentWindSpeed` float NOT NULL, 77 | `currentWindGust` float NOT NULL, 78 | `currentWindDirection` float NOT NULL, 79 | `currentWindDirectionVoltage` float NOT NULL, 80 | `totalRain` float NOT NULL, 81 | `bmp180Temperature` int(20) NOT NULL, 82 | `bmp180Pressure` float NOT NULL, 83 | `bmp180Altitude` float NOT NULL, 84 | `bmp180SeaLevel` float NOT NULL, 85 | `outsideTemperature` float NOT NULL, 86 | `outsideHumidity` float NOT NULL, 87 | `insideTemperature` float NOT NULL, 88 | `insideHumidity` float NOT NULL, 89 | PRIMARY KEY (`ID`) 90 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Weather Data' AUTO_INCREMENT=15808 ; 91 | 92 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 93 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 94 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 95 | -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirPython/README.md: -------------------------------------------------------------------------------- 1 | # 2 | # BeaconAir Source code 3 | # 4 | # SwitchDoc Labs 5 | # www.switchdoc.com 6 | # 7/8/2014 7 | # (c) 2014 under GPL2 license 8 | # 9 | # 10 | 11 | -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirPython/ble/bleThread.py: -------------------------------------------------------------------------------- 1 | # bleThread - background thread reading BLE adverts 2 | # jcs 6/8/2014 3 | # 4 | 5 | import sys 6 | import time 7 | 8 | 9 | import bluetooth._bluetooth as bluez 10 | 11 | 12 | sys.path.append('/home/pi/BeaconAir/config') 13 | sys.path.append('/home/pi/BeaconAir/ble') 14 | 15 | 16 | import blescan 17 | import utils 18 | 19 | 20 | 21 | 22 | def bleDetect(source, repeatcount, queue): 23 | 24 | 25 | 26 | 27 | dev_id = 0 28 | try: 29 | sock = bluez.hci_open_dev(dev_id) 30 | except: 31 | print "error accessing bluetooth device..." 32 | sys.exit(1) 33 | blescan.hci_le_set_scan_parameters(sock) 34 | blescan.hci_enable_le_scan(sock) 35 | 36 | 37 | while True: 38 | returnedList = blescan.parse_events(sock, repeatcount) 39 | #print "result put in queue" 40 | #print "returnList = ", returnedList 41 | queue.put(returnedList) 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirPython/ble/testblescan.py: -------------------------------------------------------------------------------- 1 | # test BLE Scanning software 2 | # jcs 6/8/2014 3 | 4 | import blescan 5 | import sys 6 | 7 | import bluetooth._bluetooth as bluez 8 | 9 | dev_id = 0 10 | try: 11 | sock = bluez.hci_open_dev(dev_id) 12 | print "ble thread started" 13 | 14 | except: 15 | print "error accessing bluetooth device..." 16 | sys.exit(1) 17 | 18 | blescan.hci_le_set_scan_parameters(sock) 19 | blescan.hci_enable_le_scan(sock) 20 | 21 | while True: 22 | returnedList = blescan.parse_events(sock, 10) 23 | print "----------" 24 | for beacon in returnedList: 25 | print beacon 26 | 27 | -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirPython/bubblelog.py: -------------------------------------------------------------------------------- 1 | # bubblelog.py 2 | # logs system information to RasPiConnect Bubble Control 3 | # 4 | # jcs 6/10/14 5 | # 6 | 7 | from time import gmtime, strftime 8 | def writeToBubbleLog(message): 9 | 10 | f = open("/home/pi/BeaconAir/state/bubblelog.txt", "a") 11 | time = strftime("%H:%M:%S", gmtime()) 12 | f.write(time+":"+message+"\n") 13 | f.close() 14 | 15 | 16 | -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirPython/iBeaconChart.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # Builds iBeaconCount graph string 4 | # filename: detection.py 5 | # Version 1.0 06/19/2014 6 | # 7 | # 8 | 9 | 10 | import sys 11 | import time 12 | 13 | import utils 14 | 15 | 16 | sys.path.append('/home/pi/BeaconAir/config') 17 | 18 | 19 | #global variables 20 | 21 | datalist = []; 22 | # if conflocal.py is not found, import default conf.py 23 | 24 | # Check for user imports 25 | try: 26 | import conflocal as conf 27 | except ImportError: 28 | import conf 29 | 30 | 31 | def buildGraphString(): 32 | 33 | global datalist 34 | 35 | response = "" 36 | valuecount = "" 37 | f = open("/home/pi/BeaconAir/state/iBeaconCountGraph.txt", "w") 38 | for i in range(len(datalist)): 39 | response += str(datalist[i]) 40 | valuecount += str(i) 41 | if (i < len(datalist)-1): 42 | response +="^^" 43 | valuecount +="^^" 44 | 45 | if (len(response) != 0): 46 | fullresponse = response + "||" + valuecount 47 | else: 48 | fullresponse = "" 49 | 50 | f.write(fullresponse) 51 | 52 | f.close() 53 | 54 | 55 | def iBeacondetect(RSSIArray): 56 | 57 | global datalist 58 | 59 | count = 0 60 | for beacon in RSSIArray: 61 | if (beacon < 0): 62 | count += 1 63 | 64 | 65 | if (len(datalist) == 10): 66 | if (len(datalist) > 0): 67 | datalist.pop(0) 68 | datalist.append(count) 69 | 70 | buildGraphString() 71 | f = open("/home/pi/BeaconAir/state/beaconCount.txt", "w") 72 | f.write(str(count)) 73 | f.close() 74 | 75 | return count 76 | -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirPython/lights.py: -------------------------------------------------------------------------------- 1 | #light control 2 | # 3 | # JCS 06/09/14 4 | # 5 | 6 | # controls the lights from Hue 7 | 8 | import sys 9 | from phue import Bridge 10 | 11 | import bubblelog 12 | 13 | # set up the hue variable 14 | hue = None 15 | 16 | sys.path.append('./config') 17 | 18 | 19 | def initializeHue(address): 20 | global hue 21 | hue = Bridge(address) 22 | 23 | def setInitialLightState(currentLightState): 24 | global hue 25 | return 26 | 27 | 28 | # if conflocal.py is not found, import default conf.py 29 | 30 | # Check for user imports 31 | try: 32 | import conflocal as conf 33 | except ImportError: 34 | import conf 35 | 36 | import utils 37 | 38 | def checkForLightTrigger (myPosition, currentDistanceSensitivity, currentBrightnessSensitivity, lightStateArray): 39 | global hue 40 | 41 | for light in conf.LightList: 42 | 43 | # check for light match 44 | lightDistance = utils.distanceBetweenTwoPoints([light[2], light[3]], myPosition) 45 | brightness = getTheBrightness(lightDistance, currentBrightnessSensitivity) 46 | if (lightDistance < currentDistanceSensitivity): 47 | print "Brightness set to: %3.2f" % brightness 48 | if (lightStateArray[light[0]] == 1): 49 | print "Light %i:%s is already ON" % (light[0], light[1]) 50 | else: 51 | print "Turn Light %i:%s ON" % (light[0], light[1]) 52 | lightStateArray[light[0]] = 1 53 | hue.set_light(light[7],'on', True) 54 | bubblelog.writeToBubbleLog("Light#%i (%s) turned ON " % (light[0], light[1]) ) 55 | #hue.set_light(light[7],'bri', (brightness *256)) 56 | 57 | elif (lightDistance > currentDistanceSensitivity): 58 | if (lightStateArray[light[0]] == 0): 59 | print "Light %i:%s is already OFF" % (light[0], light[1]) 60 | else: 61 | print "Turn Light %i:%s OFF" % (light[0], light[1]) 62 | lightStateArray[light[0]] = 0 63 | hue.set_light(light[7],'on', False) 64 | bubblelog.writeToBubbleLog("Light#%i (%s) turned OFF " % (light[0], light[1]) ) 65 | 66 | 67 | 68 | def getTheBrightness(lightDistance, currentBrightnessSensitivity): 69 | 70 | global hue 71 | newBrightness = (1.0 - lightDistance/currentBrightnessSensitivity) 72 | if (newBrightness > 1.0): 73 | newBrightness = 1.0 74 | elif (newBrightness < 0.0): 75 | newBrightness = 0.0 76 | 77 | 78 | return newBrightness 79 | 80 | 81 | def allLights(ON_OFF, lightStateArray): 82 | global hue 83 | 84 | for light in conf.LightList: 85 | print "Setting light:", light[0] 86 | if (ON_OFF == True): 87 | lightStateArray[light[0]] = 1 88 | else: 89 | lightStateArray[light[0]] = 0 90 | 91 | 92 | hue.set_light(light[7],'on', ON_OFF) 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirPython/webmap.py: -------------------------------------------------------------------------------- 1 | # webmap.py 2 | # builds the webmap code from state and configuration files 3 | # jcs 6/9/2014 4 | # 5 | import utils 6 | # if conflocal.py is not found, import default conf.py 7 | 8 | 9 | # Check for user imports 10 | try: 11 | import conflocal as conf 12 | except ImportError: 13 | import conf 14 | 15 | 16 | def buildWebMapToFile(myPosition, rollingRSSIArray, currentLightStateArray, displaybeacon, displaylights): 17 | 18 | #print currentLightStateArray 19 | 20 | f = open("/home/pi/RasPiConnectServer/Templates/W-1a.txt", "w") 21 | 22 | webresponse = "" 23 | 24 | if (displaybeacon == True): 25 | for beacon in conf.BeaconList: 26 | 27 | webresponse += "\n" 31 | 32 | #webresponse += "
\n" 52 | 53 | # now do my Position 54 | # minus means old position 55 | if ((myPosition[0] > 0.0) and (myPosition[1] > 0.0)): 56 | webresponse += "\n" 60 | else: 61 | myPosition = [-myPosition[0], -myPosition[1]] 62 | webresponse += "\n" 66 | 67 | 68 | #print webresponse 69 | f.write(webresponse) 70 | 71 | f.close() 72 | 73 | -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirRasPiConnectLocal/.Local.py.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter4Software/BeaconAirRasPiConnectLocal/.Local.py.swp -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirRasPiConnectLocal/Local.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter4Software/BeaconAirRasPiConnectLocal/Local.pyc -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirRasPiConnectLocal/LocalExample.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Filename: LocalExample.py 3 | # MiloCreek JS MiloCreek 4 | # Version 2.8 8/12/13 5 | # 6 | # Local Execute Objects for RasPiConnect 7 | # to add Execute objects, modify this file 8 | # 9 | # 10 | # 11 | # RasPiConnectServer interface constants 12 | 13 | REMOTE_WEBVIEW_UITYPE = 1 14 | ACTION_BUTTON_UITYPE = 16 15 | FEEDBACK_ACTION_BUTTON_UITYPE = 17 16 | SINGLE_LED_DISPLAY_UITYPE = 32 17 | SPEEDOMETER_UITYPE = 64 18 | VOLTMETER_UITYPE = 128 19 | BARMETER_UITYPE = 129 20 | SERVER_STATUS_UITYPE = 256 21 | PICTURE_REMOTE_WEBVIEW_UITYPE = 512 22 | LABEL_UITYPE = 1024 23 | FM_BLINK_LED_UITYPE = 2048 24 | TEXT_DISPLAY_UITYPE = 4096 25 | TOGGLE_SWITCH_UITYPE = 33 26 | SEND_TEXT_UITYPE = 34 27 | 28 | # system imports 29 | import sys 30 | import subprocess 31 | 32 | # RasPiConnectImports 33 | 34 | import Config 35 | import Validate 36 | import BuildResponse 37 | 38 | def ExecuteUserObjects(objectType, element): 39 | 40 | # Example Objects 41 | 42 | # fetch information from XML for use in user elements 43 | 44 | #objectServerID is the RasPiConnect ID from the RasPiConnect App 45 | 46 | objectServerID = element.find("./OBJECTSERVERID").text 47 | objectID = element.find("./OBJECTID").text 48 | 49 | if (Config.debug()): 50 | print("objectServerID = %s" % objectServerID) 51 | # 52 | # check to see if this is a Validate request 53 | # 54 | validate = Validate.checkForValidate(element) 55 | 56 | if (Config.debug()): 57 | print "VALIDATE=%s" % validate 58 | 59 | 60 | # Build the header for the response 61 | 62 | outgoingXMLData = BuildResponse.buildHeader(element) 63 | 64 | 65 | # objects are split up by object types by Interface Constants 66 | # 67 | # 68 | # 69 | # search for matches to object Type 70 | 71 | # object Type match 72 | if (objectType == ACTION_BUTTON_UITYPE): 73 | 74 | if (Config.debug()): 75 | print "ACTION_BUTTON_UTYPE of %s found" % objectServerID 76 | 77 | # B-2 - play a beep on the Raspberry Pi 78 | if (objectServerID == "B-2"): 79 | 80 | #check for validate request 81 | # validate allows RasPiConnect to verify this object is here 82 | if (validate == "YES"): 83 | outgoingXMLData += Validate.buildValidateResponse("YES") 84 | outgoingXMLData += BuildResponse.buildFooter() 85 | return outgoingXMLData 86 | 87 | # not validate request, so execute 88 | 89 | # note that python is in the main directory for this call, not the local directory 90 | 91 | output = subprocess.call(["aplay", "sounds/match1.wav"]) 92 | 93 | responseData = "OK" 94 | outgoingXMLData += BuildResponse.buildResponse(responseData) 95 | outgoingXMLData += BuildResponse.buildFooter() 96 | return outgoingXMLData 97 | 98 | 99 | 100 | else: 101 | return "" 102 | # returning a zero length string tells the server that you have not matched 103 | # the object and server 104 | return "" 105 | 106 | -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirRasPiConnectLocal/LocalExample.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter4Software/BeaconAirRasPiConnectLocal/LocalExample.pyc -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirRasPiConnectLocal/README.md: -------------------------------------------------------------------------------- 1 | # 2 | # Local.py file for RasPiConnect (www.milocreek.com) 3 | # 4 | # SwitchDoc Labs March 2016 5 | # 6 | # copyright GPL2 2014 7 | 8 | # 9 | 10 | March 2016 - Added BeaconAir.xml - RasPiConnect configuration file 11 | -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirRasPiConnectLocal/ST-1.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter4Software/BeaconAirRasPiConnectLocal/ST-1.txt -------------------------------------------------------------------------------- /Software/Chapter4Software/BeaconAirRasPiConnectLocal/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter4Software/BeaconAirRasPiConnectLocal/__init__.py -------------------------------------------------------------------------------- /Software/Chapter4Software/iBeacon-Scanner-/README.md: -------------------------------------------------------------------------------- 1 | SwitchDoc Labs, LLC 2 | June 2014 3 | 4 | blescanner is a python program designed to read iBeacon advertizments using a Bluetooth Dongle on a Raspberry Pi 5 | 6 | To test, "sudo python testblescanner.py" 7 | 8 | 9 | -------------------------------------------------------------------------------- /Software/Chapter4Software/iBeacon-Scanner-/testblescan.py: -------------------------------------------------------------------------------- 1 | # test BLE Scanning software 2 | # jcs 6/8/2014 3 | 4 | import blescan 5 | import sys 6 | 7 | import bluetooth._bluetooth as bluez 8 | 9 | dev_id = 0 10 | try: 11 | sock = bluez.hci_open_dev(dev_id) 12 | print "ble thread started" 13 | 14 | except: 15 | print "error accessing bluetooth device..." 16 | sys.exit(1) 17 | 18 | blescan.hci_le_set_scan_parameters(sock) 19 | blescan.hci_enable_le_scan(sock) 20 | 21 | while True: 22 | returnedList = blescan.parse_events(sock, 10) 23 | print "----------" 24 | for beacon in returnedList: 25 | print beacon 26 | 27 | -------------------------------------------------------------------------------- /Software/Chapter4Software/phue/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | #phue changelog 2 | 3 | ##r8 4 | * iOS compatibility (Nathanaël Lécaudé) 5 | * Logging fixes 6 | * Added effect changing options (bradykent) 7 | * Several unicode fixes (Nathanaël Lécaudé) 8 | * Misc bug fixes 9 | 10 | ##r7 11 | * Added to pypi 12 | * Added support for Python 3 (Nathanaël Lécaudé) 13 | * Logging level can be set with b.set_logging() (Nathanaël Lécaudé) 14 | * Logging level can be set at init: b = Bridge(logging = 'debug') (Nathanaël Lécaudé) 15 | * Added docstrings to Light properties (Nathanaël Lécaudé) 16 | * Added colormode property to Light class (Nathanaël Lécaudé) 17 | * IP is now optional if present in config file (Nathanaël Lécaudé) 18 | * Implemented groups (Nathanaël Lécaudé) 19 | * Implemented schedules (Nathanaël Lécaudé) 20 | * Renamed get_info to get_api (Nathanaël Lécaudé) 21 | * Renamed get_lights to get_light_objects (Nathanaël Lécaudé) 22 | * Renamed set_state and get_state to set_light and get_light (Nathanaël Lécaudé) 23 | * Fixed important bug when using set_state with a list of lights (Nathanaël Lécaudé) 24 | * Add access to Light objects via direct indexing of the Bridge object via __getitem__ (Marshall Perrin) 25 | * Implement real logging using Python's logging module, including error checking and display of responses from the server. (Marshall Perrin) 26 | * Add function colortemp_k for color temperatures in Kelvin. (Marshall Perrin) 27 | * Some additional error checking for invalid or missing parameters (Marshall Perrin) 28 | * More details in docstrings. (Marshall Perrin) 29 | 30 | 31 | ##r6 32 | * Light objects are now obtained using the get_lights method 33 | * Added the alert method to the Light object 34 | * All requests now use httplib for consistency 35 | * Moved all source to github 36 | * Renamed the module to phue 37 | 38 | ##r5 39 | * Renamed the Bulb() object to Light() so it reflects the official API better 40 | * You can now pass the username as argument to the Bridge class if you don't want to read/store to file 41 | * You can now get the bridge name with brdige.name or set it with bridge.name = 'newname' 42 | * The set_state method can now use a dictionary as first argument to send more complex messages 43 | -------------------------------------------------------------------------------- /Software/Chapter4Software/phue/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Nathanaël Lécaudé 4 | https://github.com/studioimaginaire/phue 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in 14 | all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /Software/Chapter4Software/phue/TODO.md: -------------------------------------------------------------------------------- 1 | #phue TODO 2 | 3 | * Find a more elegant way to deal with transitiontime 4 | * Add a Group class 5 | * Cleanup the connect and register_app methods 6 | * ~~Replace prints with proper logging mechanism~~ 7 | * ~~Read/Write config file from cwd if home is not writable~~ 8 | * ~~Store IP in config file~~ 9 | * ~~Add support for groups~~ 10 | * ~~Make username passable as argument and config file optional (so it can run when no write access is present like on iphone)~~ 11 | * ~~Rename Bulb to Light to conform to API~~ (done) 12 | * ~~Add the ability to get and set the bridge name~~ (done) 13 | * ~~Update Bulbs dictionary when lights are renamed~~ (done) 14 | -------------------------------------------------------------------------------- /Software/Chapter4Software/phue/examples/random_colors.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from phue import Bridge 3 | import random 4 | 5 | b = Bridge() # Enter bridge IP here. 6 | 7 | #If running for the first time, press button on bridge and run with b.connect() uncommented 8 | #b.connect() 9 | 10 | lights = b.get_light_objects() 11 | 12 | for light in lights: 13 | light.brightness = 254 14 | light.xy = [random.random(),random.random()] 15 | 16 | 17 | -------------------------------------------------------------------------------- /Software/Chapter4Software/phue/examples/tk_gui_complex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from Tkinter import * 3 | from phue import Bridge 4 | 5 | ''' 6 | This example creates 3 sliders for the first 3 lights 7 | and shows the name of the light under each slider. 8 | There is also a checkbox to toggle the light. 9 | ''' 10 | 11 | b = Bridge() # Enter bridge IP here. 12 | 13 | #If running for the first time, press button on bridge and run with b.connect() uncommented 14 | #b.connect() 15 | 16 | root = Tk() 17 | 18 | horizontal_frame = Frame(root) 19 | horizontal_frame.pack() 20 | 21 | lights = b.get_light_objects('id') 22 | 23 | for light_id in lights: 24 | channel_frame = Frame(horizontal_frame) 25 | channel_frame.pack(side = LEFT) 26 | 27 | scale_command = lambda x, light_id=light_id: b.set_light(light_id,{'bri': int(x), 'transitiontime': 1}) 28 | scale = Scale(channel_frame, from_ = 254, to = 0, command = scale_command, length = 200, showvalue = 0) 29 | scale.set(b.get_light(light_id,'bri')) 30 | scale.pack() 31 | 32 | button_var = BooleanVar() 33 | button_var.set(b.get_light(light_id, 'on')) 34 | button_command = lambda button_var=button_var, light_id=light_id: b.set_light(light_id, 'on', button_var.get()) 35 | button = Checkbutton(channel_frame, variable = button_var, command = button_command) 36 | button.pack() 37 | 38 | label = Label(channel_frame) 39 | label.config(text = b.get_light(light_id,'name')) 40 | label.pack() 41 | 42 | root.mainloop() -------------------------------------------------------------------------------- /Software/Chapter4Software/phue/examples/tk_gui_hsb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from Tkinter import * 3 | from phue import Bridge 4 | 5 | ''' 6 | This example creates 3 sliders for the first 3 lights 7 | and shows the name of the light under each slider. 8 | There is also a checkbox to toggle the light. 9 | ''' 10 | 11 | b = Bridge() # Enter bridge IP here. 12 | 13 | #If running for the first time, press button on bridge and run with b.connect() uncommented 14 | #b.connect() 15 | 16 | root = Tk() 17 | 18 | lights = b.get_light_objects('id') 19 | light_selection = [] 20 | 21 | 22 | def curry(fn, *cargs, **ckwargs): 23 | def call_fn(*fargs, **fkwargs): 24 | d = ckwargs.copy() 25 | d.update(fkwargs) 26 | return fn(*(cargs + fargs), **d) 27 | return call_fn 28 | 29 | def hue_command(x): 30 | if len(light_selection) > 0: 31 | b.set_light(light_selection, 'hue', int(x)) 32 | def sat_command(x): 33 | if len(light_selection) > 0: 34 | b.set_light(light_selection, 'sat', int(x)) 35 | def bri_command(x): 36 | if len(light_selection) > 0: 37 | b.set_light(light_selection, 'bri', int(x)) 38 | 39 | def select_button_command(light, button_state): 40 | global light_selection 41 | if button_state.get(): 42 | light_selection.append(light) 43 | else: 44 | light_selection.remove(light) 45 | print light_selection 46 | 47 | slider_frame = Frame(root) 48 | slider_frame.pack(pady = 10) 49 | 50 | channels_frame = Frame(root) 51 | channels_frame.pack() 52 | 53 | label_frame = Frame(channels_frame) 54 | label_frame.pack(side=LEFT, padx = 10) 55 | 56 | label_state = Label(label_frame) 57 | label_state.config(text = 'State') 58 | label_state.pack() 59 | 60 | label_select = Label(label_frame) 61 | label_select.config(text = 'Select') 62 | label_select.pack() 63 | 64 | label_name = Label(label_frame) 65 | label_name.config(text = 'Name') 66 | label_name.pack() 67 | 68 | hue_slider = Scale(slider_frame, from_ = 65535, to = 0, command = hue_command) 69 | sat_slider = Scale(slider_frame, from_ = 254, to = 0, command = sat_command) 70 | bri_slider = Scale(slider_frame, from_ = 254, to = 0, command = bri_command) 71 | hue_slider.pack(side=LEFT) 72 | sat_slider.pack(side=LEFT) 73 | bri_slider.pack(side=LEFT) 74 | 75 | 76 | for light_id in lights: 77 | channel_frame = Frame(channels_frame) 78 | channel_frame.pack(side = LEFT, padx = 10) 79 | 80 | button_var = BooleanVar() 81 | button_var.set(b.get_light(light_id, 'on')) 82 | button_command = lambda button_var=button_var, light_id=light_id: b.set_light(light_id, 'on', button_var.get()) 83 | button = Checkbutton(channel_frame, variable = button_var, command = button_command) 84 | button.pack() 85 | 86 | select_button_var = BooleanVar() 87 | #select_button_var.set(b.get_light(light_id, 'on')) 88 | select_button_callback = curry(select_button_command, light_id, select_button_var) 89 | select_button = Checkbutton(channel_frame, variable = select_button_var, command = select_button_callback) 90 | select_button.pack() 91 | 92 | label = Label(channel_frame) 93 | label.config(text = b.get_light(light_id,'name')) 94 | label.pack() 95 | 96 | root.mainloop() -------------------------------------------------------------------------------- /Software/Chapter4Software/phue/examples/tk_gui_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from Tkinter import * 3 | from phue import Bridge 4 | 5 | ''' 6 | This example creates a slider that controls the 7 | brightness of the first 3 lights. 8 | ''' 9 | 10 | b = Bridge() # Enter bridge IP here. 11 | 12 | #If running for the first time, press button on bridge and run with b.connect() uncommented 13 | #b.connect() 14 | 15 | b.set_light([1,2,3], 'on', True) 16 | 17 | def sel(data): 18 | b.set_light([1,2,3],{'bri':int(data), 'transitiontime': 1}) 19 | 20 | root = Tk() 21 | scale = Scale( root, from_ = 254, to = 0, command= sel, length = 200 ) 22 | scale.set(b.get_light(1,'bri')) 23 | scale.pack(anchor=CENTER) 24 | 25 | root.mainloop() -------------------------------------------------------------------------------- /Software/Chapter4Software/phue/phue.sublime-project: -------------------------------------------------------------------------------- 1 | { 2 | "folders": 3 | [ 4 | { 5 | "follow_symlinks": true, 6 | "path": "../phue" 7 | } 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /Software/Chapter4Software/phue/setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from setuptools import setup 4 | from phue import __version__ 5 | 6 | setup(name='phue', 7 | version=__version__, 8 | author='Nathanaël Lécaudé', 9 | url='https://github.com/studioimaginaire/phue', 10 | license='WTFPL', 11 | description='A Philips Hue Python library', 12 | long_description='A Philips Hue Python library', 13 | py_modules=['phue'], 14 | ) 15 | -------------------------------------------------------------------------------- /Software/Chapter5Software/IOTPulse/AllSerialHandling.h: -------------------------------------------------------------------------------- 1 | 2 | ////////// 3 | ///////// All Serial Handling Code, 4 | ///////// It's Changeable with the 'serialVisual' variable 5 | ///////// Set it to 'true' or 'false' when it's declared at start of code. 6 | ///////// 7 | 8 | void sendDataToSerial(char symbol, int data ); 9 | 10 | void serialOutput() { // Decide How To Output Serial. 11 | 12 | sendDataToSerial('S', Signal); // goes to sendDataToSerial function 13 | } 14 | 15 | 16 | // Decides How To OutPut BPM and IBI Data 17 | void serialOutputWhenBeatHappens() { 18 | if (serialData == true) { // Code to Make the Serial Monitor Visualizer Work 19 | Serial.print("*** Heart-Beat Happened *** "); //ASCII Art Madness 20 | Serial.print("BPM: "); 21 | Serial.print(BPM); 22 | Serial.print(" IBI: "); 23 | Serial.print(IBI); 24 | Serial.println(" "); 25 | } 26 | } 27 | 28 | 29 | 30 | // Sends Data to Pulse Sensor Processing App, Native Mac App, or Third-party Serial Readers. 31 | void sendDataToSerial(char symbol, int data ) { 32 | Serial.print(symbol); 33 | 34 | Serial.println(data); 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: cpp 3 | compiler: 4 | - g++ 5 | script: cd tests && make && make test 6 | os: 7 | - linux 8 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/CHANGES.txt: -------------------------------------------------------------------------------- 1 | 2.3 2 | * Add publish(topic,payload,retained) function 3 | 4 | 2.2 5 | * Change code layout to match Arduino Library reqs 6 | 7 | 2.1 8 | * Add MAX_TRANSFER_SIZE def to chunk messages if needed 9 | * Reject topic/payloads that exceed MQTT_MAX_PACKET_SIZE 10 | 11 | 2.0 12 | * Add (and default to) MQTT 3.1.1 support 13 | * Fix PROGMEM handling for Intel Galileo/ESP8266 14 | * Add overloaded constructors for convenience 15 | * Add chainable setters for server/callback/client/stream 16 | * Add state function to return connack return code 17 | 18 | 1.9 19 | * Do not split MQTT packets over multiple calls to _client->write() 20 | * API change: All constructors now require an instance of Client 21 | to be passed in. 22 | * Fixed example to match 1.8 api changes - dpslwk 23 | * Added username/password support - WilHall 24 | * Added publish_P - publishes messages from PROGMEM - jobytaffey 25 | 26 | 1.8 27 | * KeepAlive interval is configurable in PubSubClient.h 28 | * Maximum packet size is configurable in PubSubClient.h 29 | * API change: Return boolean rather than int from various functions 30 | * API change: Length parameter in message callback changed 31 | from int to unsigned int 32 | * Various internal tidy-ups around types 33 | 1.7 34 | * Improved keepalive handling 35 | * Updated to the Arduino-1.0 API 36 | 1.6 37 | * Added the ability to publish a retained message 38 | 39 | 1.5 40 | * Added default constructor 41 | * Fixed compile error when used with arduino-0021 or later 42 | 43 | 1.4 44 | * Fixed connection lost handling 45 | 46 | 1.3 47 | * Fixed packet reading bug in PubSubClient.readPacket 48 | 49 | 1.2 50 | * Fixed compile error when used with arduino-0016 or later 51 | 52 | 53 | 1.1 54 | * Reduced size of library 55 | * Added support for Will messages 56 | * Clarified licensing - see LICENSE.txt 57 | 58 | 59 | 1.0 60 | * Only Quality of Service (QOS) 0 messaging is supported 61 | * The maximum message size, including header, is 128 bytes 62 | * The keepalive interval is set to 30 seconds 63 | * No support for Will messages 64 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2008-2015 Nicholas O'Leary 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/README.md: -------------------------------------------------------------------------------- 1 | # Arduino Client for MQTT 2 | 3 | This library provides a client for doing simple publish/subscribe messaging with 4 | a server that supports MQTT. 5 | 6 | ## Examples 7 | 8 | The library comes with a number of example sketches. See File > Examples > PubSubClient 9 | within the Arduino application. 10 | 11 | Full API documentation is available here: http://pubsubclient.knolleary.net 12 | 13 | ## Limitations 14 | 15 | - It can only publish QoS 0 messages. It can subscribe at QoS 0 or QoS 1. 16 | - The maximum message size, including header, is **128 bytes** by default. This 17 | is configurable via `MQTT_MAX_PACKET_SIZE` in `PubSubClient.h`. 18 | - The keepalive interval is set to 15 seconds by default. This is configurable 19 | via `MQTT_KEEPALIVE` in `PubSubClient.h`. 20 | - The client uses MQTT 3.1.1 by default. It can be changed to use MQTT 3.1 by 21 | changing value of `MQTT_VERSION` in `PubSubClient.h`. 22 | 23 | 24 | ## Compatible Hardware 25 | 26 | The library uses the Arduino Ethernet Client api for interacting with the 27 | underlying network hardware. This means it Just Works with a growing number of 28 | boards and shields, including: 29 | 30 | - Arduino Ethernet 31 | - Arduino Ethernet Shield 32 | - Arduino YUN – use the included `YunClient` in place of `EthernetClient`, and 33 | be sure to do a `Bridge.begin()` first 34 | - Arduino WiFi Shield - if you want to send packets > 90 bytes with this shield, 35 | enable the `MQTT_MAX_TRANSFER_SIZE` define in `PubSubClient.h`. 36 | - Sparkfun WiFly Shield – [library](https://github.com/dpslwk/WiFly) 37 | - TI CC3000 WiFi - [library](https://github.com/sparkfun/SFE_CC3000_Library) 38 | - Intel Galileo/Edison 39 | - ESP8266 40 | 41 | The library cannot currently be used with hardware based on the ENC28J60 chip – 42 | such as the Nanode or the Nuelectronics Ethernet Shield. For those, there is an 43 | [alternative library](https://github.com/njh/NanodeMQTT) available. 44 | 45 | ## License 46 | 47 | This code is released under the MIT License. 48 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/examples/mqtt_auth/mqtt_auth.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Basic MQTT example with Authentication 3 | 4 | - connects to an MQTT server, providing username 5 | and password 6 | - publishes "hello world" to the topic "outTopic" 7 | - subscribes to the topic "inTopic" 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | // Update these with values suitable for your network. 15 | byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; 16 | IPAddress ip(172, 16, 0, 100); 17 | IPAddress server(172, 16, 0, 2); 18 | 19 | void callback(char* topic, byte* payload, unsigned int length) { 20 | // handle message arrived 21 | } 22 | 23 | EthernetClient ethClient; 24 | PubSubClient client(server, 1883, callback, ethClient); 25 | 26 | void setup() 27 | { 28 | Ethernet.begin(mac, ip); 29 | // Note - the default maximum packet size is 128 bytes. If the 30 | // combined length of clientId, username and password exceed this, 31 | // you will need to increase the value of MQTT_MAX_PACKET_SIZE in 32 | // PubSubClient.h 33 | 34 | if (client.connect("arduinoClient", "testuser", "testpass")) { 35 | client.publish("outTopic","hello world"); 36 | client.subscribe("inTopic"); 37 | } 38 | } 39 | 40 | void loop() 41 | { 42 | client.loop(); 43 | } 44 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/examples/mqtt_basic/mqtt_basic.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Basic MQTT example 3 | 4 | This sketch demonstrates the basic capabilities of the library. 5 | It connects to an MQTT server then: 6 | - publishes "hello world" to the topic "outTopic" 7 | - subscribes to the topic "inTopic", printing out any messages 8 | it receives. NB - it assumes the received payloads are strings not binary 9 | 10 | It will reconnect to the server if the connection is lost using a blocking 11 | reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to 12 | achieve the same result without blocking the main loop. 13 | 14 | */ 15 | 16 | #include 17 | #include 18 | #include 19 | 20 | // Update these with values suitable for your network. 21 | byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; 22 | IPAddress ip(172, 16, 0, 100); 23 | IPAddress server(172, 16, 0, 2); 24 | 25 | void callback(char* topic, byte* payload, unsigned int length) { 26 | Serial.print("Message arrived ["); 27 | Serial.print(topic); 28 | Serial.print("] "); 29 | for (int i=0;i 18 | #include 19 | #include 20 | 21 | // Update these with values suitable for your network. 22 | byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; 23 | IPAddress ip(172, 16, 0, 100); 24 | IPAddress server(172, 16, 0, 2); 25 | 26 | // Callback function header 27 | void callback(char* topic, byte* payload, unsigned int length); 28 | 29 | EthernetClient ethClient; 30 | PubSubClient client(server, 1883, callback, ethClient); 31 | 32 | // Callback function 33 | void callback(char* topic, byte* payload, unsigned int length) { 34 | // In order to republish this payload, a copy must be made 35 | // as the orignal payload buffer will be overwritten whilst 36 | // constructing the PUBLISH packet. 37 | 38 | // Allocate the correct amount of memory for the payload copy 39 | byte* p = (byte*)malloc(length); 40 | // Copy the payload to the new buffer 41 | memcpy(p,payload,length); 42 | client.publish("outTopic", p, length); 43 | // Free the memory 44 | free(p); 45 | } 46 | 47 | void setup() 48 | { 49 | 50 | Ethernet.begin(mac, ip); 51 | if (client.connect("arduinoClient")) { 52 | client.publish("outTopic","hello world"); 53 | client.subscribe("inTopic"); 54 | } 55 | } 56 | 57 | void loop() 58 | { 59 | client.loop(); 60 | } 61 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/examples/mqtt_reconnect_nonblocking/mqtt_reconnect_nonblocking.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Reconnecting MQTT example - non-blocking 3 | 4 | This sketch demonstrates how to keep the client connected 5 | using a non-blocking reconnect function. If the client loses 6 | its connection, it attempts to reconnect every 5 seconds 7 | without blocking the main loop. 8 | 9 | */ 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | // Update these with values suitable for your hardware/network. 16 | byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; 17 | IPAddress ip(172, 16, 0, 100); 18 | IPAddress server(172, 16, 0, 2); 19 | 20 | void callback(char* topic, byte* payload, unsigned int length) { 21 | // handle message arrived 22 | } 23 | 24 | EthernetClient ethClient; 25 | PubSubClient client(ethClient); 26 | 27 | long lastReconnectAttempt = 0; 28 | 29 | boolean reconnect() { 30 | if (client.connect("arduinoClient")) { 31 | // Once connected, publish an announcement... 32 | client.publish("outTopic","hello world"); 33 | // ... and resubscribe 34 | client.subscribe("inTopic"); 35 | } 36 | return client.connected(); 37 | } 38 | 39 | void setup() 40 | { 41 | client.setServer(server, 1883); 42 | client.setCallback(callback); 43 | 44 | Ethernet.begin(mac, ip); 45 | delay(1500); 46 | lastReconnectAttempt = 0; 47 | } 48 | 49 | 50 | void loop() 51 | { 52 | if (!client.connected()) { 53 | long now = millis(); 54 | if (now - lastReconnectAttempt > 5000) { 55 | lastReconnectAttempt = now; 56 | // Attempt to reconnect 57 | if (reconnect()) { 58 | lastReconnectAttempt = 0; 59 | } 60 | } 61 | } else { 62 | // Client connected 63 | 64 | client.loop(); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/examples/mqtt_stream/mqtt_stream.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Example of using a Stream object to store the message payload 3 | 4 | Uses SRAM library: https://github.com/ennui2342/arduino-sram 5 | but could use any Stream based class such as SD 6 | 7 | - connects to an MQTT server 8 | - publishes "hello world" to the topic "outTopic" 9 | - subscribes to the topic "inTopic" 10 | */ 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | // Update these with values suitable for your network. 18 | byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; 19 | IPAddress ip(172, 16, 0, 100); 20 | IPAddress server(172, 16, 0, 2); 21 | 22 | SRAM sram(4, SRAM_1024); 23 | 24 | void callback(char* topic, byte* payload, unsigned int length) { 25 | sram.seek(1); 26 | 27 | // do something with the message 28 | for(uint8_t i=0; i 4 | maintainer=Nick O'Leary 5 | sentence=A client library for MQTT messaging. 6 | paragraph=MQTT is a lightweight messaging protocol ideal for small devices. This library allows you to send and receive MQTT messages. It supports the latest MQTT 3.1.1 protocol and can be configured to use the older MQTT 3.1 if needed. It supports all Arduino Ethernet Client compatible hardware, including the Intel Galileo/Edison, ESP8266 and TI CC3000. 7 | category=Communication 8 | url=http://pubsubclient.knolleary.net 9 | architectures=* 10 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/Makefile: -------------------------------------------------------------------------------- 1 | SRC_PATH=./src 2 | OUT_PATH=./bin 3 | TEST_SRC=$(wildcard ${SRC_PATH}/*_spec.cpp) 4 | TEST_BIN= $(TEST_SRC:${SRC_PATH}/%.cpp=${OUT_PATH}/%) 5 | VPATH=${SRC_PATH} 6 | SHIM_FILES=${SRC_PATH}/lib/*.cpp 7 | PSC_FILE=../src/PubSubClient.cpp 8 | CC=g++ 9 | CFLAGS=-I${SRC_PATH}/lib -I../src 10 | 11 | all: $(TEST_BIN) 12 | 13 | ${OUT_PATH}/%: ${SRC_PATH}/%.cpp ${PSC_FILE} ${SHIM_FILES} 14 | mkdir -p ${OUT_PATH} 15 | ${CC} ${CFLAGS} $^ -o $@ 16 | 17 | clean: 18 | @rm -rf ${OUT_PATH} 19 | 20 | test: 21 | @bin/connect_spec 22 | @bin/publish_spec 23 | @bin/receive_spec 24 | @bin/subscribe_spec 25 | @bin/keepalive_spec 26 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/README.md: -------------------------------------------------------------------------------- 1 | # Arduino Client for MQTT Test Suite 2 | 3 | This is a regression test suite for the `PubSubClient` library. 4 | 5 | There are two parts: 6 | 7 | - Tests that can be compiled and run on any machine 8 | - Tests that build the example sketches using the Arduino IDE 9 | 10 | 11 | It is a work-in-progress and is subject to complete refactoring as the whim takes 12 | me. 13 | 14 | 15 | ## Local tests 16 | 17 | These are a set of executables that can be run to test specific areas of functionality. 18 | They do not require a real Arduino to be attached, nor the use of the Arduino IDE. 19 | 20 | The tests include a set of mock files to stub out the parts of the Arduino environment the library 21 | depends on. 22 | 23 | ### Dependencies 24 | 25 | - g++ 26 | 27 | ### Running 28 | 29 | Build the tests using the provided `Makefile`: 30 | 31 | $ make 32 | 33 | This will create a set of executables in `./bin/`. Run each of these executables to test the corresponding functionality. 34 | 35 | *Note:* the `connect_spec` and `keepalive_spec` tests involve testing keepalive timers so naturally take a few minutes to run through. 36 | 37 | ## Arduino tests 38 | 39 | *Note:* INO Tool doesn't currently play nicely with Arduino 1.5. This has broken this test suite. 40 | 41 | Without a suitable arduino plugged in, the test suite will only check the 42 | example sketches compile cleanly against the library. 43 | 44 | With an arduino plugged in, each sketch that has a corresponding python 45 | test case is built, uploaded and then the tests run. 46 | 47 | ### Dependencies 48 | 49 | - Python 2.7+ 50 | - [INO Tool](http://inotool.org/) - this provides command-line build/upload of Arduino sketches 51 | 52 | ### Running 53 | 54 | The test suite _does not_ run an MQTT server - it is assumed to be running already. 55 | 56 | $ python testsuite.py 57 | 58 | A summary of activity is printed to the console. More comprehensive logs are written 59 | to the `logs` directory. 60 | 61 | ### What it does 62 | 63 | For each sketch in the library's `examples` directory, e.g. `mqtt_basic.ino`, the suite looks for a matching test case 64 | `testcases/mqtt_basic.py`. 65 | 66 | The test case must follow these conventions: 67 | - sub-class `unittest.TestCase` 68 | - provide the class methods `setUpClass` and `tearDownClass` (TODO: make this optional) 69 | - all test method names begin with `test_` 70 | 71 | The suite will call the `setUpClass` method _before_ uploading the sketch. This 72 | allows any test setup to be performed before the sketch runs - such as connecting 73 | a client and subscribing to topics. 74 | 75 | 76 | ### Settings 77 | 78 | The file `testcases/settings.py` is used to config the test environment. 79 | 80 | - `server_ip` - the IP address of the broker the client should connect to (the broker port is assumed to be 1883). 81 | - `arduino_ip` - the IP address the arduino should use (when not testing DHCP). 82 | 83 | Before each sketch is compiled, these values are automatically substituted in. To 84 | do this, the suite looks for lines that _start_ with the following: 85 | 86 | byte server[] = { 87 | byte ip[] = { 88 | 89 | and replaces them with the appropriate values. 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/Arduino.h: -------------------------------------------------------------------------------- 1 | #ifndef Arduino_h 2 | #define Arduino_h 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | 10 | extern "C"{ 11 | typedef uint8_t byte ; 12 | typedef uint8_t boolean ; 13 | 14 | /* sketch */ 15 | extern void setup( void ) ; 16 | extern void loop( void ) ; 17 | uint32_t millis( void ); 18 | } 19 | 20 | #define PROGMEM 21 | #define pgm_read_byte_near(x) *(x) 22 | 23 | #endif // Arduino_h 24 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/BDDTest.cpp: -------------------------------------------------------------------------------- 1 | #include "BDDTest.h" 2 | #include "trace.h" 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | int testCount = 0; 9 | int testPasses = 0; 10 | const char* testDescription; 11 | 12 | std::list failureList; 13 | 14 | void bddtest_suite(const char* name) { 15 | LOG(name << "\n"); 16 | } 17 | 18 | int bddtest_test(const char* file, int line, const char* assertion, int result) { 19 | if (!result) { 20 | LOG("✗\n"); 21 | std::ostringstream os; 22 | os << " ! "<::iterator it = failureList.begin(); it != failureList.end(); it++) { 40 | LOG("\n"); 41 | LOG(*it); 42 | LOG("\n"); 43 | } 44 | 45 | LOG(std::dec << testPasses << "/" << testCount << " tests passed\n\n"); 46 | if (testPasses == testCount) { 47 | return 0; 48 | } 49 | return 1; 50 | } 51 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/BDDTest.h: -------------------------------------------------------------------------------- 1 | #ifndef bddtest_h 2 | #define bddtest_h 3 | 4 | void bddtest_suite(const char* name); 5 | int bddtest_test(const char*, int, const char*, int); 6 | void bddtest_start(const char*); 7 | void bddtest_end(); 8 | int bddtest_summary(); 9 | 10 | #define SUITE(x) { bddtest_suite(x); } 11 | #define TEST(x) { if (!bddtest_test(__FILE__, __LINE__, #x, (x))) return false; } 12 | 13 | #define IT(x) { bddtest_start(x); } 14 | #define END_IT { bddtest_end();return true;} 15 | 16 | #define FINISH { return bddtest_summary(); } 17 | 18 | #define IS_TRUE(x) TEST(x) 19 | #define IS_FALSE(x) TEST(!(x)) 20 | #define IS_EQUAL(x,y) TEST(x==y) 21 | #define IS_NOT_EQUAL(x,y) TEST(x!=y) 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/Buffer.cpp: -------------------------------------------------------------------------------- 1 | #include "Buffer.h" 2 | #include "Arduino.h" 3 | 4 | Buffer::Buffer() { 5 | } 6 | 7 | Buffer::Buffer(uint8_t* buf, size_t size) { 8 | this->add(buf,size); 9 | } 10 | bool Buffer::available() { 11 | return this->pos < this->length; 12 | } 13 | 14 | uint8_t Buffer::next() { 15 | if (this->available()) { 16 | return this->buffer[this->pos++]; 17 | } 18 | return 0; 19 | } 20 | 21 | void Buffer::reset() { 22 | this->pos = 0; 23 | } 24 | 25 | void Buffer::add(uint8_t* buf, size_t size) { 26 | uint16_t i = 0; 27 | for (;ibuffer[this->length++] = buf[i]; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/Buffer.h: -------------------------------------------------------------------------------- 1 | #ifndef buffer_h 2 | #define buffer_h 3 | 4 | #include "Arduino.h" 5 | 6 | class Buffer { 7 | private: 8 | uint8_t buffer[1024]; 9 | uint16_t pos; 10 | uint16_t length; 11 | 12 | public: 13 | Buffer(); 14 | Buffer(uint8_t* buf, size_t size); 15 | 16 | virtual bool available(); 17 | virtual uint8_t next(); 18 | virtual void reset(); 19 | 20 | virtual void add(uint8_t* buf, size_t size); 21 | }; 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/Client.h: -------------------------------------------------------------------------------- 1 | #ifndef client_h 2 | #define client_h 3 | #include "IPAddress.h" 4 | 5 | class Client { 6 | public: 7 | virtual int connect(IPAddress ip, uint16_t port) =0; 8 | virtual int connect(const char *host, uint16_t port) =0; 9 | virtual size_t write(uint8_t) =0; 10 | virtual size_t write(const uint8_t *buf, size_t size) =0; 11 | virtual int available() = 0; 12 | virtual int read() = 0; 13 | virtual int read(uint8_t *buf, size_t size) = 0; 14 | virtual int peek() = 0; 15 | virtual void flush() = 0; 16 | virtual void stop() = 0; 17 | virtual uint8_t connected() = 0; 18 | virtual operator bool() = 0; 19 | }; 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/IPAddress.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | IPAddress::IPAddress() 6 | { 7 | memset(_address, 0, sizeof(_address)); 8 | } 9 | 10 | IPAddress::IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet) 11 | { 12 | _address[0] = first_octet; 13 | _address[1] = second_octet; 14 | _address[2] = third_octet; 15 | _address[3] = fourth_octet; 16 | } 17 | 18 | IPAddress::IPAddress(uint32_t address) 19 | { 20 | memcpy(_address, &address, sizeof(_address)); 21 | } 22 | 23 | IPAddress::IPAddress(const uint8_t *address) 24 | { 25 | memcpy(_address, address, sizeof(_address)); 26 | } 27 | 28 | IPAddress& IPAddress::operator=(const uint8_t *address) 29 | { 30 | memcpy(_address, address, sizeof(_address)); 31 | return *this; 32 | } 33 | 34 | IPAddress& IPAddress::operator=(uint32_t address) 35 | { 36 | memcpy(_address, (const uint8_t *)&address, sizeof(_address)); 37 | return *this; 38 | } 39 | 40 | bool IPAddress::operator==(const uint8_t* addr) 41 | { 42 | return memcmp(addr, _address, sizeof(_address)) == 0; 43 | } 44 | 45 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/IPAddress.h: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * MIT License: 4 | * Copyright (c) 2011 Adrian McEwen 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy 6 | * of this software and associated documentation files (the "Software"), to deal 7 | * in the Software without restriction, including without limitation the rights 8 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | * copies of the Software, and to permit persons to whom the Software is 10 | * furnished to do so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in 13 | * all copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | * THE SOFTWARE. 22 | * 23 | * adrianm@mcqn.com 1/1/2011 24 | */ 25 | 26 | #ifndef IPAddress_h 27 | #define IPAddress_h 28 | 29 | 30 | // A class to make it easier to handle and pass around IP addresses 31 | 32 | class IPAddress { 33 | private: 34 | uint8_t _address[4]; // IPv4 address 35 | // Access the raw byte array containing the address. Because this returns a pointer 36 | // to the internal structure rather than a copy of the address this function should only 37 | // be used when you know that the usage of the returned uint8_t* will be transient and not 38 | // stored. 39 | uint8_t* raw_address() { return _address; }; 40 | 41 | public: 42 | // Constructors 43 | IPAddress(); 44 | IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet); 45 | IPAddress(uint32_t address); 46 | IPAddress(const uint8_t *address); 47 | 48 | // Overloaded cast operator to allow IPAddress objects to be used where a pointer 49 | // to a four-byte uint8_t array is expected 50 | operator uint32_t() { return *((uint32_t*)_address); }; 51 | bool operator==(const IPAddress& addr) { return (*((uint32_t*)_address)) == (*((uint32_t*)addr._address)); }; 52 | bool operator==(const uint8_t* addr); 53 | 54 | // Overloaded index operator to allow getting and setting individual octets of the address 55 | uint8_t operator[](int index) const { return _address[index]; }; 56 | uint8_t& operator[](int index) { return _address[index]; }; 57 | 58 | // Overloaded copy operators to allow initialisation of IPAddress objects from other types 59 | IPAddress& operator=(const uint8_t *address); 60 | IPAddress& operator=(uint32_t address); 61 | 62 | 63 | friend class EthernetClass; 64 | friend class UDP; 65 | friend class Client; 66 | friend class Server; 67 | friend class DhcpClass; 68 | friend class DNSClient; 69 | }; 70 | 71 | 72 | #endif 73 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/ShimClient.h: -------------------------------------------------------------------------------- 1 | #ifndef shimclient_h 2 | #define shimclient_h 3 | 4 | #include "Arduino.h" 5 | #include "Client.h" 6 | #include "IPAddress.h" 7 | #include "Buffer.h" 8 | 9 | 10 | class ShimClient : public Client { 11 | private: 12 | Buffer* responseBuffer; 13 | Buffer* expectBuffer; 14 | bool _allowConnect; 15 | bool _connected; 16 | bool expectAnything; 17 | bool _error; 18 | uint16_t _received; 19 | IPAddress _expectedIP; 20 | uint16_t _expectedPort; 21 | const char* _expectedHost; 22 | 23 | public: 24 | ShimClient(); 25 | virtual int connect(IPAddress ip, uint16_t port); 26 | virtual int connect(const char *host, uint16_t port); 27 | virtual size_t write(uint8_t); 28 | virtual size_t write(const uint8_t *buf, size_t size); 29 | virtual int available(); 30 | virtual int read(); 31 | virtual int read(uint8_t *buf, size_t size); 32 | virtual int peek(); 33 | virtual void flush(); 34 | virtual void stop(); 35 | virtual uint8_t connected(); 36 | virtual operator bool(); 37 | 38 | virtual ShimClient* respond(uint8_t *buf, size_t size); 39 | virtual ShimClient* expect(uint8_t *buf, size_t size); 40 | 41 | virtual void expectConnect(IPAddress ip, uint16_t port); 42 | virtual void expectConnect(const char *host, uint16_t port); 43 | 44 | virtual uint16_t received(); 45 | virtual bool error(); 46 | 47 | virtual void setAllowConnect(bool b); 48 | virtual void setConnected(bool b); 49 | }; 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/Stream.cpp: -------------------------------------------------------------------------------- 1 | #include "Stream.h" 2 | #include "trace.h" 3 | #include 4 | #include 5 | 6 | Stream::Stream() { 7 | this->expectBuffer = new Buffer(); 8 | this->_error = false; 9 | this->_written = 0; 10 | } 11 | 12 | size_t Stream::write(uint8_t b) { 13 | this->_written++; 14 | TRACE(std::hex << (unsigned int)b); 15 | if (this->expectBuffer->available()) { 16 | uint8_t expected = this->expectBuffer->next(); 17 | if (expected != b) { 18 | this->_error = true; 19 | TRACE("!=" << (unsigned int)expected); 20 | } 21 | } else { 22 | this->_error = true; 23 | } 24 | TRACE("\n"<< std::dec); 25 | return 1; 26 | } 27 | 28 | 29 | bool Stream::error() { 30 | return this->_error; 31 | } 32 | 33 | void Stream::expect(uint8_t *buf, size_t size) { 34 | this->expectBuffer->add(buf,size); 35 | } 36 | 37 | uint16_t Stream::length() { 38 | return this->_written; 39 | } 40 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/Stream.h: -------------------------------------------------------------------------------- 1 | #ifndef Stream_h 2 | #define Stream_h 3 | 4 | #include "Arduino.h" 5 | #include "Buffer.h" 6 | 7 | class Stream { 8 | private: 9 | Buffer* expectBuffer; 10 | bool _error; 11 | uint16_t _written; 12 | 13 | public: 14 | Stream(); 15 | virtual size_t write(uint8_t); 16 | 17 | virtual bool error(); 18 | virtual void expect(uint8_t *buf, size_t size); 19 | virtual uint16_t length(); 20 | }; 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/src/lib/trace.h: -------------------------------------------------------------------------------- 1 | #ifndef trace_h 2 | #define trace_h 3 | #include 4 | 5 | #include 6 | 7 | #define LOG(x) {std::cout << x << std::flush; } 8 | #define TRACE(x) {if (getenv("TRACE")) { std::cout << x << std::flush; }} 9 | 10 | #endif 11 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/testcases/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter5Software/pubsubclient/tests/testcases/__init__.py -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/testcases/mqtt_basic.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import settings 3 | 4 | import time 5 | import mosquitto 6 | 7 | import serial 8 | 9 | def on_message(mosq, obj, msg): 10 | obj.message_queue.append(msg) 11 | 12 | class mqtt_basic(unittest.TestCase): 13 | 14 | message_queue = [] 15 | 16 | @classmethod 17 | def setUpClass(self): 18 | self.client = mosquitto.Mosquitto("pubsubclient_ut", clean_session=True,obj=self) 19 | self.client.connect(settings.server_ip) 20 | self.client.on_message = on_message 21 | self.client.subscribe("outTopic",0) 22 | 23 | @classmethod 24 | def tearDownClass(self): 25 | self.client.disconnect() 26 | 27 | def test_one(self): 28 | i=30 29 | while len(self.message_queue) == 0 and i > 0: 30 | self.client.loop() 31 | time.sleep(0.5) 32 | i -= 1 33 | self.assertTrue(i>0, "message receive timed-out") 34 | self.assertEqual(len(self.message_queue), 1, "unexpected number of messages received") 35 | msg = self.message_queue[0] 36 | self.assertEqual(msg.mid,0,"message id not 0") 37 | self.assertEqual(msg.topic,"outTopic","message topic incorrect") 38 | self.assertEqual(msg.payload,"hello world") 39 | self.assertEqual(msg.qos,0,"message qos not 0") 40 | self.assertEqual(msg.retain,False,"message retain flag incorrect") 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/testcases/mqtt_publish_in_callback.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import settings 3 | 4 | import time 5 | import mosquitto 6 | 7 | import serial 8 | 9 | def on_message(mosq, obj, msg): 10 | obj.message_queue.append(msg) 11 | 12 | class mqtt_publish_in_callback(unittest.TestCase): 13 | 14 | message_queue = [] 15 | 16 | @classmethod 17 | def setUpClass(self): 18 | self.client = mosquitto.Mosquitto("pubsubclient_ut", clean_session=True,obj=self) 19 | self.client.connect(settings.server_ip) 20 | self.client.on_message = on_message 21 | self.client.subscribe("outTopic",0) 22 | 23 | @classmethod 24 | def tearDownClass(self): 25 | self.client.disconnect() 26 | 27 | def test_connect(self): 28 | i=30 29 | while len(self.message_queue) == 0 and i > 0: 30 | self.client.loop() 31 | time.sleep(0.5) 32 | i -= 1 33 | self.assertTrue(i>0, "message receive timed-out") 34 | self.assertEqual(len(self.message_queue), 1, "unexpected number of messages received") 35 | msg = self.message_queue.pop(0) 36 | self.assertEqual(msg.mid,0,"message id not 0") 37 | self.assertEqual(msg.topic,"outTopic","message topic incorrect") 38 | self.assertEqual(msg.payload,"hello world") 39 | self.assertEqual(msg.qos,0,"message qos not 0") 40 | self.assertEqual(msg.retain,False,"message retain flag incorrect") 41 | 42 | 43 | def test_publish(self): 44 | self.assertEqual(len(self.message_queue), 0, "message queue not empty") 45 | payload = "abcdefghij" 46 | self.client.publish("inTopic",payload) 47 | 48 | i=30 49 | while len(self.message_queue) == 0 and i > 0: 50 | self.client.loop() 51 | time.sleep(0.5) 52 | i -= 1 53 | 54 | self.assertTrue(i>0, "message receive timed-out") 55 | self.assertEqual(len(self.message_queue), 1, "unexpected number of messages received") 56 | msg = self.message_queue.pop(0) 57 | self.assertEqual(msg.mid,0,"message id not 0") 58 | self.assertEqual(msg.topic,"outTopic","message topic incorrect") 59 | self.assertEqual(msg.payload,payload) 60 | self.assertEqual(msg.qos,0,"message qos not 0") 61 | self.assertEqual(msg.retain,False,"message retain flag incorrect") 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /Software/Chapter5Software/pubsubclient/tests/testcases/settings.py: -------------------------------------------------------------------------------- 1 | server_ip = "172.16.0.2" 2 | arduino_ip = "172.16.0.100" 3 | -------------------------------------------------------------------------------- /Software/Chapter6Software/IOTRFID/Utils.h: -------------------------------------------------------------------------------- 1 | 2 | void blinkLED(int timesToBlink, int delayBetweenBlinks) 3 | { 4 | 5 | int i; 6 | for (i = 0; i < timesToBlink; i++) 7 | { 8 | digitalWrite(blinkPin, 0); 9 | delay(delayBetweenBlinks / 2); 10 | digitalWrite(blinkPin, 1); 11 | delay(delayBetweenBlinks / 2); 12 | 13 | } 14 | 15 | } 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Software/Chapter6Software/IOTRFID/seeedRFID.h: -------------------------------------------------------------------------------- 1 | /* 2 | * SeeedRFID.h 3 | * A library for RFID moudle. 4 | * 5 | * Copyright (c) 2008-2014 seeed technology inc. 6 | * Author : Ye Xiaobo(yexiaobo@seeedstudio.com) 7 | * Create Time: 2014/2/20 8 | * 9 | * The MIT License (MIT) 10 | * 11 | * Permission is hereby granted, free of charge, to any person obtaining a copy 12 | * of this software and associated documentation files (the "Software"), to deal 13 | * in the Software without restriction, including without limitation the rights 14 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 15 | * copies of the Software, and to permit persons to whom the Software is 16 | * furnished to do so, subject to the following conditions: 17 | * 18 | * The above copyright notice and this permission notice shall be included in 19 | * all copies or substantial portions of the Software. 20 | * 21 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 22 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 25 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 26 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 27 | * THE SOFTWARE. 28 | */ 29 | 30 | /************************************************************************** 31 | * Pins 32 | * ==== 33 | * 34 | * 1. VCC support 3.3 ~ 5V 35 | * 2. TX, RX connect to Arduino or Seeeduino 36 | * 3. T1, T2 is the Signal port for RFID antenna 37 | * 4. W0, W1 is for wiegand protocol, but this library not support yet. 38 | * 39 | * ``` 40 | * +-----------+ 41 | * ----|VCC T1|---- 42 | * ----|GND T2|---- 43 | * ----|TX SER|---- 44 | * ----|RX LED|---- 45 | * ----|W0 BEEP|---- 46 | * ----|W1 GND|---- 47 | * +-----------+ 48 | * ``` 49 | ***************************************************************************/ 50 | 51 | #ifndef SeeedRFID_H 52 | #define SeeedRFID_H 53 | 54 | #include 55 | #include "Arduino.h" 56 | 57 | struct RFIDdata 58 | { 59 | int dataLen; 60 | byte chk; 61 | boolean valid; 62 | unsigned char raw[5]; 63 | }; 64 | 65 | enum RFIDType 66 | { 67 | RFID_UART, 68 | RFID_WIEGAND 69 | }; 70 | 71 | class SeeedRFID 72 | { 73 | private: 74 | SoftwareSerial * _rfidIO; // software serail 75 | RFIDdata _data; 76 | boolean _isAvailable; 77 | RFIDType _type; 78 | boolean checkBitValidationUART(); 79 | boolean read(); 80 | public: 81 | SeeedRFID(int rxPin, int txPin); 82 | ~SeeedRFID(); 83 | 84 | boolean isAvailable(); 85 | RFIDdata data(); 86 | unsigned long cardNumber(); 87 | }; 88 | 89 | #endif //__SeeedRFID_H__ 90 | -------------------------------------------------------------------------------- /Software/Chapter6Software/SDL_PI_IOTDataCollector/IOTCollector.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # IOT Data Collector 4 | # 5 | # SwitchDoc Labs 6 | # December 2015 7 | # 8 | 9 | import httplib2 as http 10 | import json 11 | 12 | import time 13 | 14 | import SolarPowerESP8266 15 | 16 | 17 | try: 18 | from urlparse import urlparse 19 | except ImportError: 20 | from urllib.parse import urlparse 21 | 22 | # fetch the JSON data from the IOT device 23 | def fetchJSONData(uri, path): 24 | target = urlparse(uri+path) 25 | method = 'GET' 26 | body = '' 27 | 28 | h = http.Http() 29 | 30 | # If you need authentication some example: 31 | #if auth: 32 | # h.add_credentials(auth.user, auth.password) 33 | 34 | response, content = h.request( 35 | target.geturl(), 36 | method, 37 | body, 38 | headers) 39 | 40 | # assume that content is a json reply 41 | # parse content with the json module 42 | data = json.loads(content) 43 | 44 | return data 45 | 46 | headers = { 47 | 'Accept': 'application/json', 48 | 'Content-Type': 'application/json; charset=UTF-8' 49 | } 50 | 51 | # main program 52 | uri = 'http://192.168.1.129' 53 | path = '/' 54 | 55 | 56 | 57 | while True: 58 | 59 | data = fetchJSONData(uri, path) 60 | 61 | if (data['name'] == "SolarPowerESP8266"): 62 | SolarPowerESP8266.parseSolarPowerESP8266(data) 63 | 64 | #print( data['id'], data['name']) 65 | 66 | time.sleep(60.0) 67 | -------------------------------------------------------------------------------- /Software/Chapter6Software/SDL_PI_IOTDataCollector/README.md: -------------------------------------------------------------------------------- 1 | 2 | IOTDataCollector 3 | 4 | SwitchDoc Labs 5 | December 2015 6 | 7 | This code is used for various IOT devices being built by SwitchDoc Labs such as LightSwarm, WeatherPi and SolarPowerESP8266 8 | 9 | Make sure you replace the IP address to match your IOT REST interface 10 | 11 | 12 | -------------------------------------------------------------------------------- /Software/Chapter6Software/SDL_PI_IOTDataCollector/SolarPowerESP8266.py: -------------------------------------------------------------------------------- 1 | # 2 | # SolarPowerESP8266 3 | # 4 | # parsing and storage data 5 | # 6 | # SwitchDoc Labs 7 | # December 2015 8 | # 9 | import time 10 | import datetime 11 | 12 | import MySQLdb as mdb 13 | 14 | def parseSolarPowerESP8266(data): 15 | 16 | type = data["name"] 17 | deviceid = data["id"] 18 | timestamp = data["variables"]["RestTimeStamp"] 19 | dataString = data["variables"]["RestDataString"] 20 | firmwareversion = data["variables"]["FirmwareVersion"] 21 | 22 | ts = time.time() 23 | receivedTimeStamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') 24 | print "%s: sampling SolarPowerESP8266 data" % receivedTimeStamp 25 | 26 | 27 | #print "%s: type= %s deviceid=%s timestamp=%s dataString=%s" % (receivedTimeStamp, type, deviceid, timestamp, dataString) 28 | 29 | 30 | con = mdb.connect('localhost', 'root', 'password', 'IOTSolarData'); 31 | 32 | 33 | # you must create a Cursor object. It will let 34 | # you execute all the queries you need 35 | cur = con.cursor() 36 | 37 | # read all data out of JSON 38 | samples = dataString.split("|") 39 | 40 | if (len(samples) > 1): 41 | # we have data 42 | 43 | print "%i sample(s) read" % (len(samples) -1) 44 | for i in range(len(samples)): 45 | 46 | values = samples[i].split(',') 47 | if (i == 0): 48 | heap_available = int(samples[i]) 49 | else: 50 | sample_timestamp = int(values[0]) 51 | battery_load_voltage = float(values[2]) 52 | battery_current = float(values[3]) 53 | solarcell_load_voltage = float(values[5]) 54 | solarcell_current = float(values[6]) 55 | output_load_voltage = float(values[8]) 56 | output_current = float(values[9]) 57 | 58 | query = 'INSERT INTO SolarPowerData(timestamp,type, deviceid, firmwareversion, heap_available, sample_timestamp, battery_load_voltage, battery_current, solarcell_load_voltage, solarcell_current, output_load_voltage, output_current) VALUES(UTC_TIMESTAMP(), "%s", "%s", "%s", %d, %d, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f)' %( type, deviceid, firmwareversion, heap_available, sample_timestamp, battery_load_voltage, battery_current, solarcell_load_voltage, solarcell_current, output_load_voltage, output_current) 59 | #print("query=%s" % query) 60 | 61 | cur.execute(query) 62 | 63 | con.commit() 64 | -------------------------------------------------------------------------------- /Software/Chapter6Software/SDL_PI_IOTDataCollector/static/solarcurrentgraph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter6Software/SDL_PI_IOTDataCollector/static/solarcurrentgraph.png -------------------------------------------------------------------------------- /Software/Chapter6Software/SDL_PI_IOTDataCollector/static/solarvoltagegraph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/raspberry-pi-iot-projects/7f29d82ed26eecd49ee768a55a43156a1020d598/Software/Chapter6Software/SDL_PI_IOTDataCollector/static/solarvoltagegraph.png -------------------------------------------------------------------------------- /Software/Chapter6Software/SDL_PI_IOTDataCollector/updateGraphs.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # updates all SolarPowerESP8266 Graphs 4 | # 5 | # SwitchDoc Labs 6 | # December 2015 7 | # 8 | # 9 | import SolarPowerESP8266VoltageGraph 10 | import SolarPowerESP8266CurrentGraph 11 | 12 | 13 | SolarPowerESP8266VoltageGraph.SolarPowerESP8266VoltageGraph("updateGraphs", 10) 14 | SolarPowerESP8266CurrentGraph.SolarPowerESP8266CurrentGraph("updateGraphs", 10) 15 | 16 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/README.md: -------------------------------------------------------------------------------- 1 | Arduino AESLib 2 | ============== 3 | 4 | This project is just an Arduino ready extract from the [AVR-Crypto-Lib](https://github.com/cantora/avr-crypto-lib). 5 | 6 | It only packages the ASM implementations of AES into a library ready to use in 7 | Arduino IDE. 8 | 9 | See the LICENSE file for details of the GPLv3 license in which the AVR-Crypo-Lib 10 | is licensed. 11 | 12 | 13 | Installation 14 | ------------ 15 | 16 | - Download the files in this repository (using either clone or the download button) 17 | - Copy the `AESLib` folder into `libraries` folder (same level as your `sketch` folder) 18 | - add `#include ` in your sketch. 19 | 20 | 21 | Usage 22 | ----- 23 | 24 | At the moment only 128bit keys are supported, the blocksize is also fixed at 128bit. 25 | This means that the key array and possible iv array should contain exactly 16 bytes (`uint8_t` or `byte`). 26 | Moreover the amount of bytes to encrypt should be mod 16. 27 | (this means you have to take care of padding yourself). 28 | 29 | The library supports 3 kinds of operations. 30 | 31 | 1. single block encryption/decryption 32 | - multiple block encryption/decryption using CBC (single call) 33 | - multiple block encryption/decryption using CBC (multiple calls) 34 | 35 | The single block enc/decryption are the following methods: 36 | 37 | ```c 38 | void aes128_enc_single(const uint8_t* key, void* data); 39 | void aes128_dec_single(const uint8_t* key, void* data); 40 | ``` 41 | 42 | Usage example: 43 | 44 | ```c 45 | Serial.begin(57600); 46 | uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; 47 | char data[] = "0123456789012345"; //16 chars == 16 bytes 48 | aes128_enc_single(key, data); 49 | Serial.print("encrypted:"); 50 | Serial.println(data); 51 | aes128_dec_single(key, data); 52 | Serial.print("decrypted:"); 53 | Serial.println(data); 54 | ``` 55 | 56 | Usage example for AES256: 57 | 58 | ```c 59 | Serial.begin(57600); 60 | uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}; 61 | char data[] = "0123456789012345"; 62 | aes256_enc_single(key, data); 63 | Serial.print("encrypted:"); 64 | Serial.println(data); 65 | aes256_dec_single(key, data); 66 | Serial.print("decrypted:"); 67 | Serial.println(data); 68 | ``` 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes.h: -------------------------------------------------------------------------------- 1 | /* aes.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-30 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | #ifndef AES_H_ 28 | #define AES_H_ 29 | 30 | #include 31 | 32 | #include "aes_types.h" 33 | #include "aes128_enc.h" 34 | #include "aes192_enc.h" 35 | #include "aes256_enc.h" 36 | #include "aes128_dec.h" 37 | #include "aes192_dec.h" 38 | #include "aes256_dec.h" 39 | #include "aes_enc.h" 40 | #include "aes_dec.h" 41 | #include "aes_keyschedule.h" 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes128_dec.h: -------------------------------------------------------------------------------- 1 | /* aes128_dec.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes128_dec.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-30 24 | * \license GPLv3 or later 25 | * \ingroup AES 26 | */ 27 | 28 | #ifndef AES128_DEC_H_ 29 | #define AES128_DEC_H_ 30 | 31 | #include "aes_types.h" 32 | #include "aes_dec.h" 33 | 34 | /** 35 | * \brief decrypt with 128 bit key. 36 | * 37 | * This function decrypts one block with the AES algorithm under control of 38 | * a keyschedule produced from a 128 bit key. 39 | * \param buffer pointer to the block to decrypt 40 | * \param ctx pointer to the key schedule 41 | */ 42 | void aes128_dec(void* buffer, aes128_ctx_t* ctx); 43 | 44 | 45 | 46 | #endif /* AES128_DEC_H_ */ 47 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes128_enc.h: -------------------------------------------------------------------------------- 1 | /* aes128_enc.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes128_enc.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-30 24 | * \license GPLv3 or later 25 | * \ingroup AES 26 | */ 27 | 28 | #ifndef AES128_ENC_H_ 29 | #define AES128_ENC_H_ 30 | 31 | #include "aes_types.h" 32 | #include "aes_enc.h" 33 | 34 | 35 | /** 36 | * \brief encrypt with 128 bit key. 37 | * 38 | * This function encrypts one block with the AES algorithm under control of 39 | * a keyschedule produced from a 128 bit key. 40 | * \param buffer pointer to the block to encrypt 41 | * \param ctx pointer to the key schedule 42 | */ 43 | void aes128_enc(void* buffer, aes128_ctx_t* ctx); 44 | 45 | 46 | 47 | #endif /* AES128_ENC_H_ */ 48 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes192_dec.h: -------------------------------------------------------------------------------- 1 | /* aes192_dec.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes192_dec.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-31 24 | * \license GPLv3 or later 25 | * \ingroup AES 26 | */ 27 | 28 | #ifndef AES192_DEC_H_ 29 | #define AES192_DEC_H_ 30 | 31 | #include "aes_types.h" 32 | #include "aes_dec.h" 33 | 34 | /** 35 | * \brief decrypt with 192 bit key. 36 | * 37 | * This function decrypts one block with the AES algorithm under control of 38 | * a keyschedule produced from a 192 bit key. 39 | * \param buffer pointer to the block to decrypt 40 | * \param ctx pointer to the key schedule 41 | */ 42 | void aes192_dec(void* buffer, aes192_ctx_t* ctx); 43 | 44 | 45 | 46 | #endif /* AES192_DEC_H_ */ 47 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes192_enc.h: -------------------------------------------------------------------------------- 1 | /* aes192_enc.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes192_enc.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-31 24 | * \license GPLv3 or later 25 | * \ingroup AES 26 | */ 27 | 28 | #ifndef AES192_ENC_H_ 29 | #define AES192_ENC_H_ 30 | 31 | #include "aes_types.h" 32 | #include "aes_enc.h" 33 | 34 | 35 | /** 36 | * \brief encrypt with 192 bit key. 37 | * 38 | * This function encrypts one block with the AES algorithm under control of 39 | * a keyschedule produced from a 192 bit key. 40 | * \param buffer pointer to the block to encrypt 41 | * \param ctx pointer to the key schedule 42 | */ 43 | void aes192_enc(void* buffer, aes192_ctx_t* ctx); 44 | 45 | 46 | 47 | #endif /* AES192_ENC_H_ */ 48 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes256_dec.h: -------------------------------------------------------------------------------- 1 | /* aes256_dec.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes256_dec.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-31 24 | * \license GPLv3 or later 25 | * \ingroup AES 26 | */ 27 | 28 | #ifndef AES256_DEC_H_ 29 | #define AES256_DEC_H_ 30 | 31 | #include "aes_types.h" 32 | #include "aes_dec.h" 33 | 34 | /** 35 | * \brief decrypt with 256 bit key. 36 | * 37 | * This function decrypts one block with the AES algorithm under control of 38 | * a keyschedule produced from a 256 bit key. 39 | * \param buffer pointer to the block to decrypt 40 | * \param ctx pointer to the key schedule 41 | */ 42 | void aes256_dec(void* buffer, aes256_ctx_t* ctx); 43 | 44 | 45 | 46 | #endif /* AES256_DEC_H_ */ 47 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes256_enc.h: -------------------------------------------------------------------------------- 1 | /* aes256_enc.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes256_enc.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-31 24 | * \license GPLv3 or later 25 | * \ingroup AES 26 | */ 27 | 28 | #ifndef AES256_ENC_H_ 29 | #define AES256_ENC_H_ 30 | 31 | #include "aes_types.h" 32 | #include "aes_enc.h" 33 | 34 | 35 | /** 36 | * \brief encrypt with 256 bit key. 37 | * 38 | * This function encrypts one block with the AES algorithm under control of 39 | * a keyschedule produced from a 256 bit key. 40 | * \param buffer pointer to the block to encrypt 41 | * \param ctx pointer to the key schedule 42 | */ 43 | void aes256_enc(void* buffer, aes256_ctx_t* ctx); 44 | 45 | 46 | 47 | #endif /* AES256_ENC_H_ */ 48 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes_dec.h: -------------------------------------------------------------------------------- 1 | /* aes_dec.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes_dec.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-30 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | #ifndef AES_DEC_H_ 28 | #define AES_DEC_H_ 29 | #include "aes_types.h" 30 | #include 31 | 32 | 33 | void aes_decrypt_core(aes_cipher_state_t* state,const aes_genctx_t* ks, uint8_t rounds); 34 | 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes_enc.h: -------------------------------------------------------------------------------- 1 | /* aes_enc.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes_enc.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-30 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | #ifndef AES_ENC_H_ 28 | #define AES_ENC_H_ 29 | #include "aes_types.h" 30 | #include 31 | 32 | 33 | void aes_encrypt_core(aes_cipher_state_t* state, const aes_genctx_t* ks, uint8_t rounds); 34 | 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes_invsbox-asm.S: -------------------------------------------------------------------------------- 1 | /* aes_sbox-asm.S */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008, 2009 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes_dec-asm.S 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2009-01-10 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | .balign 256 28 | .global aes_invsbox 29 | aes_invsbox: 30 | .byte 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb 31 | .byte 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb 32 | .byte 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e 33 | .byte 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 34 | .byte 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92 35 | .byte 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 36 | .byte 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06 37 | .byte 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b 38 | .byte 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73 39 | .byte 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e 40 | .byte 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b 41 | .byte 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4 42 | .byte 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f 43 | .byte 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef 44 | .byte 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 45 | .byte 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d 46 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes_invsbox.h: -------------------------------------------------------------------------------- 1 | /* aes_invsbox.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes_invsbox.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-30 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | #ifndef AES_INVSBOX_H_ 28 | #define AES_INVSBOX_H_ 29 | #include 30 | 31 | extern uint8_t aes_invsbox[]; 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes_keyschedule.h: -------------------------------------------------------------------------------- 1 | /* aes_keyschedule.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes_keyschedule.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-30 24 | * \license GPLv3 or later 25 | * \ingroup AES 26 | */ 27 | 28 | 29 | #ifndef AES_KEYSCHEDULE_H_ 30 | #define AES_KEYSCHEDULE_H_ 31 | 32 | #include "aes_types.h" 33 | /** 34 | * \brief initialize the keyschedule 35 | * 36 | * This function computes the keyschedule from a given key with a given length 37 | * and stores it in the context variable 38 | * \param key pointer to the key material 39 | * \param keysize_b length of the key in bits (valid are 128, 192 and 256) 40 | * \param ctx pointer to the context where the keyschedule should be stored 41 | */ 42 | void aes_init(const void* key, uint16_t keysize_b, aes_genctx_t* ctx); 43 | 44 | /** 45 | * \brief initialize the keyschedule for 128 bit key 46 | * 47 | * This function computes the keyschedule from a given 128 bit key 48 | * and stores it in the context variable 49 | * \param key pointer to the key material 50 | * \param ctx pointer to the context where the keyschedule should be stored 51 | */ 52 | void aes128_init(const void* key, aes128_ctx_t* ctx); 53 | 54 | /** 55 | * \brief initialize the keyschedule for 192 bit key 56 | * 57 | * This function computes the keyschedule from a given 192 bit key 58 | * and stores it in the context variable 59 | * \param key pointer to the key material 60 | * \param ctx pointer to the context where the keyschedule should be stored 61 | */ 62 | void aes192_init(const void* key, aes192_ctx_t* ctx); 63 | 64 | /** 65 | * \brief initialize the keyschedule for 256 bit key 66 | * 67 | * This function computes the keyschedule from a given 256 bit key 68 | * and stores it in the context variable 69 | * \param key pointer to the key material 70 | * \param ctx pointer to the context where the keyschedule should be stored 71 | */ 72 | void aes256_init(const void* key, aes256_ctx_t* ctx); 73 | 74 | #endif /* AES_KEYSCHEDULE_H_ */ 75 | 76 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes_sbox-asm.S: -------------------------------------------------------------------------------- 1 | /* aes_sbox-asm.S */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008, 2009 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes_dec-asm.S 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2009-01-10 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | 28 | .balign 256 29 | .global aes_sbox 30 | aes_sbox: 31 | .byte 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76 32 | .byte 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0 33 | .byte 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15 34 | .byte 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75 35 | .byte 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84 36 | .byte 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf 37 | .byte 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8 38 | .byte 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2 39 | .byte 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73 40 | .byte 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb 41 | .byte 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79 42 | .byte 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08 43 | .byte 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a 44 | .byte 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e 45 | .byte 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf 46 | .byte 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 47 | 48 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes_sbox.h: -------------------------------------------------------------------------------- 1 | /* aes_sbox.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes_sbox.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-30 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | #ifndef AES_SBOX_H_ 28 | #define AES_SBOX_H_ 29 | #include 30 | 31 | extern uint8_t aes_sbox[]; 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/aes_types.h: -------------------------------------------------------------------------------- 1 | /* aes.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file aes_types.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2008-12-30 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | #ifndef AES_TYPES_H_ 28 | #define AES_TYPES_H_ 29 | 30 | #include 31 | 32 | typedef struct{ 33 | uint8_t ks[16]; 34 | } aes_roundkey_t; 35 | 36 | typedef struct{ 37 | aes_roundkey_t key[10+1]; 38 | } aes128_ctx_t; 39 | 40 | typedef struct{ 41 | aes_roundkey_t key[12+1]; 42 | } aes192_ctx_t; 43 | 44 | typedef struct{ 45 | aes_roundkey_t key[14+1]; 46 | } aes256_ctx_t; 47 | 48 | typedef struct{ 49 | aes_roundkey_t key[1]; /* just to avoid the warning */ 50 | } aes_genctx_t; 51 | 52 | typedef struct{ 53 | uint8_t s[16]; 54 | } aes_cipher_state_t; 55 | 56 | #endif 57 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal-basic.c: -------------------------------------------------------------------------------- 1 | /* bcal-basic.c */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2009 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include "blockcipher_descriptor.h" 25 | #include "keysize_descriptor.h" 26 | 27 | uint8_t bcal_cipher_init(const bcdesc_t* cipher_descriptor, 28 | const void* key, uint16_t keysize_b, bcgen_ctx_t* ctx){ 29 | if(!is_valid_keysize_P((PGM_VOID_P)pgm_read_word(&(cipher_descriptor->valid_keysize_desc)), 30 | keysize_b)){ 31 | return 1; 32 | } 33 | uint8_t flags; 34 | bc_init_fpt init_fpt; 35 | ctx->desc_ptr = (bcdesc_t*)cipher_descriptor; 36 | ctx->keysize = keysize_b; 37 | flags = pgm_read_byte(cipher_descriptor->flags); 38 | init_fpt.initvoid = (void_fpt)(pgm_read_word(&(cipher_descriptor->init.initvoid))); 39 | if(init_fpt.initvoid == NULL){ 40 | if(!(ctx->ctx = malloc((keysize_b+7)/8))) 41 | return 2; 42 | memcpy(ctx->ctx, key, (keysize_b+7)/8); 43 | return 0; 44 | } 45 | if(!(ctx->ctx = malloc(pgm_read_word(&(cipher_descriptor->ctxsize_B))))) 46 | return 3; 47 | if((flags&BC_INIT_TYPE)==BC_INIT_TYPE_1){ 48 | init_fpt.init1((void*)key, (ctx->ctx)); 49 | }else{ 50 | init_fpt.init2((void*)key, keysize_b, (ctx->ctx)); 51 | } 52 | return 0; 53 | } 54 | 55 | void bcal_cipher_free(bcgen_ctx_t* ctx){ 56 | if(!ctx) 57 | return; 58 | bc_free_fpt free_fpt; 59 | free_fpt = (bc_free_fpt)(pgm_read_word(&(ctx->desc_ptr->free))); 60 | if(free_fpt) 61 | free_fpt((ctx->ctx)); 62 | free(ctx->ctx); 63 | } 64 | 65 | void bcal_cipher_enc(void* block, const bcgen_ctx_t* ctx){ 66 | bc_enc_fpt enc_fpt; 67 | enc_fpt.encvoid = (void_fpt)pgm_read_word(&(ctx->desc_ptr->enc.encvoid)); 68 | if(!enc_fpt.encvoid){ 69 | /* very bad error, no enciphering function specified */ 70 | return; 71 | } 72 | enc_fpt.enc1(block, (ctx->ctx)); 73 | 74 | } 75 | 76 | void bcal_cipher_dec(void* block, const bcgen_ctx_t* ctx){ 77 | bc_dec_fpt dec_fpt; 78 | dec_fpt.decvoid = (void_fpt)pgm_read_word(&(ctx->desc_ptr->dec.decvoid)); 79 | if(!dec_fpt.decvoid){ 80 | /* very bad error, no deciphering function specified */ 81 | return; 82 | } 83 | dec_fpt.dec1(block, (ctx->ctx)); 84 | } 85 | 86 | uint16_t bcal_cipher_getBlocksize_b(const bcdesc_t* desc){ 87 | return pgm_read_word(&(desc->blocksize_b)); 88 | } 89 | 90 | PGM_VOID_P bcal_cipher_getKeysizeDesc(const bcdesc_t* desc){ 91 | return (PGM_VOID_P)pgm_read_word(&(desc->valid_keysize_desc)); 92 | } 93 | 94 | 95 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal-basic.h: -------------------------------------------------------------------------------- 1 | /* bcal-basic.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2009 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | #ifndef BCAL_BASIC_H_ 21 | #define BCAL_BASIC_H_ 22 | 23 | #include 24 | #include 25 | #include "blockcipher_descriptor.h" 26 | #include "keysize_descriptor.h" 27 | #include 28 | 29 | uint8_t bcal_cipher_init(const bcdesc_t* cipher_descriptor, 30 | const void* key, uint16_t keysize_b, bcgen_ctx_t* ctx); 31 | void bcal_cipher_free(bcgen_ctx_t* ctx); 32 | void bcal_cipher_enc(void* block, const bcgen_ctx_t* ctx); 33 | void bcal_cipher_dec(void* block, const bcgen_ctx_t* ctx); 34 | uint16_t bcal_cipher_getBlocksize_b(const bcdesc_t* desc); 35 | PGM_VOID_P bcal_cipher_getKeysizeDesc(const bcdesc_t* desc); 36 | #endif /* BCAL_BASIC_H_ */ 37 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal-cbc.c: -------------------------------------------------------------------------------- 1 | /* bcal-cbc.c */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2010 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | #include 21 | #include 22 | #include "bcal-cbc.h" 23 | #include "bcal-basic.h" 24 | #include "memxor.h" 25 | 26 | uint8_t bcal_cbc_init(const bcdesc_t* desc, const void* key, uint16_t keysize_b, bcal_cbc_ctx_t* ctx){ 27 | ctx->desc = (bcdesc_t*)desc; 28 | ctx->blocksize_B = (bcal_cipher_getBlocksize_b(desc)+7)/8; 29 | ctx->prev_block = malloc(ctx->blocksize_B); 30 | 31 | if(ctx->prev_block==NULL){ 32 | return 0x11; 33 | } 34 | return bcal_cipher_init(desc, key, keysize_b, &(ctx->cctx)); 35 | } 36 | 37 | void bcal_cbc_free(bcal_cbc_ctx_t* ctx){ 38 | bcal_cipher_free(&(ctx->cctx)); 39 | free(ctx->prev_block); 40 | } 41 | 42 | 43 | void bcal_cbc_loadIV(const void* iv, bcal_cbc_ctx_t* ctx){ 44 | if(iv){ 45 | memcpy(ctx->prev_block, iv, ctx->blocksize_B); 46 | } 47 | } 48 | 49 | void bcal_cbc_encNext(void* block, bcal_cbc_ctx_t* ctx){ 50 | memxor(block, ctx->prev_block, ctx->blocksize_B); 51 | bcal_cipher_enc(block, &(ctx->cctx)); 52 | memcpy(ctx->prev_block, block, ctx->blocksize_B); 53 | } 54 | 55 | void bcal_cbc_decNext(void* block, bcal_cbc_ctx_t* ctx){ 56 | uint8_t tmp[ctx->blocksize_B]; 57 | memcpy(tmp, block, ctx->blocksize_B); 58 | bcal_cipher_dec(block, &(ctx->cctx)); 59 | memxor(block, ctx->prev_block, ctx->blocksize_B); 60 | memcpy(ctx->prev_block, tmp, ctx->blocksize_B); 61 | } 62 | void bcal_cbc_decRand(void* block, const void* prev_block, bcal_cbc_ctx_t* ctx){ 63 | bcal_cipher_dec(block, &(ctx->cctx)); 64 | memxor(block, prev_block, ctx->blocksize_B); 65 | } 66 | 67 | void bcal_cbc_encMsg(const void* iv, void* msg, uint16_t msg_blocks, bcal_cbc_ctx_t* ctx){ 68 | bcal_cbc_loadIV(iv, ctx); 69 | while(msg_blocks--){ 70 | bcal_cbc_encNext(msg, ctx); 71 | msg = (uint8_t*)msg + ctx->blocksize_B; 72 | } 73 | } 74 | 75 | void bcal_cbc_decMsg(const void* iv, void* msg, uint16_t msg_blocks, bcal_cbc_ctx_t* ctx){ 76 | msg=(uint8_t*)msg + (msg_blocks-1)*ctx->blocksize_B; 77 | while(msg_blocks > 1){ 78 | bcal_cbc_decRand(msg, (uint8_t*)msg-ctx->blocksize_B, ctx); 79 | msg_blocks -= 1; 80 | msg=(uint8_t*)msg-ctx->blocksize_B; 81 | } 82 | bcal_cbc_decRand(msg, iv, ctx); 83 | } 84 | 85 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal-cbc.h: -------------------------------------------------------------------------------- 1 | /* bcal-cbc.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2010 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | #ifndef BCALCBC_H_ 21 | #define BCALCBC_H_ 22 | 23 | #include 24 | #include "blockcipher_descriptor.h" 25 | #include "bcal-basic.h" 26 | 27 | typedef struct{ 28 | bcdesc_t* desc; 29 | bcgen_ctx_t cctx; 30 | uint8_t* prev_block; 31 | uint8_t blocksize_B; 32 | } bcal_cbc_ctx_t; 33 | 34 | uint8_t bcal_cbc_init(const bcdesc_t* desc, const void* key, uint16_t keysize_b, bcal_cbc_ctx_t* ctx); 35 | void bcal_cbc_free(bcal_cbc_ctx_t* ctx); 36 | void bcal_cbc_loadIV(const void* iv, bcal_cbc_ctx_t* ctx); 37 | void bcal_cbc_encNext(void* block, bcal_cbc_ctx_t* ctx); 38 | void bcal_cbc_decNext(void* block, bcal_cbc_ctx_t* ctx); 39 | void bcal_cbc_decRand(void* block, const void* prev_block, bcal_cbc_ctx_t* ctx); 40 | void bcal_cbc_encMsg(const void* iv, void* msg, uint16_t msg_blocks, bcal_cbc_ctx_t* ctx); 41 | void bcal_cbc_decMsg(const void* iv, void* msg, uint16_t msg_blocks, bcal_cbc_ctx_t* ctx); 42 | 43 | 44 | #endif /* BCALCBC_H_ */ 45 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal-cmac.h: -------------------------------------------------------------------------------- 1 | /* bcal-cmac.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2010 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | #ifndef BCALCMAC_H_ 21 | #define BCALCMAC_H_ 22 | 23 | #include 24 | #include "bcal-basic.h" 25 | #include "blockcipher_descriptor.h" 26 | 27 | typedef struct{ 28 | bcdesc_t* desc; 29 | bcgen_ctx_t cctx; 30 | uint8_t* accu; 31 | uint8_t* k1; 32 | uint8_t* k2; 33 | uint8_t* lastblock; 34 | uint8_t last_set; 35 | uint8_t blocksize_B; 36 | } bcal_cmac_ctx_t; 37 | 38 | uint8_t bcal_cmac_init(const bcdesc_t* desc, const void* key, uint16_t keysize_b, bcal_cmac_ctx_t* ctx); 39 | void bcal_cmac_free(bcal_cmac_ctx_t* ctx); 40 | void bcal_cmac_nextBlock(bcal_cmac_ctx_t* ctx, const void* block); 41 | void bcal_cmac_lastBlock(bcal_cmac_ctx_t* ctx, const void* block, uint16_t length_b); 42 | void bcal_cmac_ctx2mac(void* dest, uint16_t length_b, const bcal_cmac_ctx_t* ctx); 43 | void bcal_cmac(void* dest, uint16_t out_length_b, const void* block, uint32_t length_b, bcal_cmac_ctx_t* ctx); 44 | 45 | #endif /* BCALCMAC_H_ */ 46 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal-ofb.c: -------------------------------------------------------------------------------- 1 | /* bcal-ofb.c */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2010 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | #include 21 | #include 22 | #include "bcal-ofb.h" 23 | #include "bcal-basic.h" 24 | #include "memxor.h" 25 | 26 | 27 | uint8_t bcal_ofb_init(const bcdesc_t* desc, const void* key, uint16_t keysize_b, bcal_ofb_ctx_t* ctx){ 28 | ctx->desc = (bcdesc_t*)desc; 29 | ctx->blocksize_B = (bcal_cipher_getBlocksize_b(desc)+7)/8; 30 | ctx->in_block=malloc(ctx->blocksize_B); 31 | if(ctx->in_block==NULL){ 32 | return 0x11; 33 | } 34 | return bcal_cipher_init(desc, key, keysize_b, &(ctx->cctx)); 35 | } 36 | 37 | void bcal_ofb_free(bcal_ofb_ctx_t* ctx){ 38 | free(ctx->in_block); 39 | bcal_cipher_free(&(ctx->cctx)); 40 | } 41 | 42 | void bcal_ofb_loadIV(const void* iv, bcal_ofb_ctx_t* ctx){ 43 | if(iv){ 44 | memcpy(ctx->in_block, iv, ctx->blocksize_B); 45 | } 46 | } 47 | 48 | void bcal_ofb_encNext(void* block, bcal_ofb_ctx_t* ctx){ 49 | bcal_cipher_enc(ctx->in_block , &(ctx->cctx)); 50 | memxor(block, ctx->in_block, ctx->blocksize_B); 51 | } 52 | 53 | void bcal_ofb_decNext(void* block, bcal_ofb_ctx_t* ctx){ 54 | bcal_cipher_enc(ctx->in_block , &(ctx->cctx)); 55 | memxor(block, ctx->in_block, ctx->blocksize_B); 56 | } 57 | 58 | 59 | void bcal_ofb_encMsg(const void* iv, void* msg, uint32_t msg_len_b, bcal_ofb_ctx_t* ctx){ 60 | uint16_t block_len_b; 61 | block_len_b = ctx->blocksize_B*8; 62 | bcal_ofb_loadIV(iv, ctx); 63 | while(msg_len_b>block_len_b){ 64 | bcal_ofb_encNext(msg, ctx); 65 | msg_len_b -= block_len_b; 66 | msg = (uint8_t*)msg + ctx->blocksize_B; 67 | } 68 | bcal_cipher_enc(ctx->in_block, &(ctx->cctx)); 69 | ctx->in_block[msg_len_b/8] = 0xff00>>(msg_len_b&7); 70 | memxor(msg, ctx->in_block, (msg_len_b+7)/8); 71 | } 72 | 73 | void bcal_ofb_decMsg(const void* iv, void* msg, uint32_t msg_len_b, bcal_ofb_ctx_t* ctx){ 74 | bcal_ofb_encMsg(iv, msg, msg_len_b, ctx); 75 | } 76 | 77 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal-ofb.h: -------------------------------------------------------------------------------- 1 | /* bcal-ofb.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2010 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | 21 | #ifndef BCALOFB_H_ 22 | #define BCALOFB_H_ 23 | 24 | #include 25 | #include "bcal-basic.h" 26 | #include "blockcipher_descriptor.h" 27 | 28 | 29 | typedef struct{ 30 | bcdesc_t* desc; 31 | bcgen_ctx_t cctx; 32 | uint8_t* in_block; 33 | uint8_t blocksize_B; 34 | } bcal_ofb_ctx_t; 35 | 36 | 37 | uint8_t bcal_ofb_init(const bcdesc_t* desc, const void* key, uint16_t keysize_b, bcal_ofb_ctx_t* ctx); 38 | void bcal_ofb_free(bcal_ofb_ctx_t* ctx); 39 | void bcal_ofb_loadIV(const void* iv, bcal_ofb_ctx_t* ctx); 40 | void bcal_ofb_encNext(void* block, bcal_ofb_ctx_t* ctx); 41 | void bcal_ofb_decNext(void* block, bcal_ofb_ctx_t* ctx); 42 | void bcal_ofb_encMsg(const void* iv, void* msg, uint32_t msg_len_b, bcal_ofb_ctx_t* ctx); 43 | void bcal_ofb_decMsg(const void* iv, void* msg, uint32_t msg_len_b, bcal_ofb_ctx_t* ctx); 44 | 45 | 46 | #endif /* BCALOFB_H_ */ 47 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal_aes128.c: -------------------------------------------------------------------------------- 1 | /* bcal_aes128.c */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file bcal_aes128.c 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2009-01-08 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | 28 | #include 29 | #include 30 | #include "blockcipher_descriptor.h" 31 | #include "aes.h" 32 | #include "aes128_enc.h" 33 | #include "aes128_dec.h" 34 | #include "aes_keyschedule.h" 35 | #include "keysize_descriptor.h" 36 | 37 | const char aes128_str[] PROGMEM = "AES-128"; 38 | 39 | const uint8_t aes128_keysize_desc[] PROGMEM = { KS_TYPE_LIST, 1, KS_INT(128), 40 | KS_TYPE_TERMINATOR }; 41 | 42 | const bcdesc_t aes128_desc PROGMEM = { 43 | BCDESC_TYPE_BLOCKCIPHER, 44 | BC_INIT_TYPE_1, 45 | aes128_str, 46 | sizeof(aes128_ctx_t), 47 | 128, 48 | {(void_fpt)aes128_init}, 49 | {(void_fpt)aes128_enc}, 50 | {(void_fpt)aes128_dec}, 51 | (bc_free_fpt)NULL, 52 | aes128_keysize_desc 53 | }; 54 | 55 | 56 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal_aes128.h: -------------------------------------------------------------------------------- 1 | /* bcal_aes128.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file bcal_aes128.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2009-01-08 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | 28 | #include 29 | #include "blockcipher_descriptor.h" 30 | #include "aes.h" 31 | #include "aes128_enc.h" 32 | #include "aes128_dec.h" 33 | #include "keysize_descriptor.h" 34 | 35 | extern const bcdesc_t aes128_desc; 36 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal_aes192.c: -------------------------------------------------------------------------------- 1 | /* bcal_aes192.c */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file bcal_aes192.c 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2009-01-08 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | 28 | #include 29 | #include 30 | #include "blockcipher_descriptor.h" 31 | #include "aes.h" 32 | #include "aes192_enc.h" 33 | #include "aes192_dec.h" 34 | #include "aes_keyschedule.h" 35 | #include "keysize_descriptor.h" 36 | 37 | const char aes192_str[] PROGMEM = "AES-192"; 38 | 39 | const uint8_t aes192_keysize_desc[] PROGMEM = { KS_TYPE_LIST, 1, KS_INT(192), 40 | KS_TYPE_TERMINATOR }; 41 | 42 | const bcdesc_t aes192_desc PROGMEM = { 43 | BCDESC_TYPE_BLOCKCIPHER, 44 | BC_INIT_TYPE_1, 45 | aes192_str, 46 | sizeof(aes192_ctx_t), 47 | 128, 48 | {(void_fpt)aes192_init}, 49 | {(void_fpt)aes192_enc}, 50 | {(void_fpt)aes192_dec}, 51 | (bc_free_fpt)NULL, 52 | aes192_keysize_desc 53 | }; 54 | 55 | 56 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal_aes192.h: -------------------------------------------------------------------------------- 1 | /* bcal_aes192.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file bcal_aes192.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2009-01-08 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | 28 | #include 29 | #include "blockcipher_descriptor.h" 30 | #include "aes.h" 31 | #include "aes192_enc.h" 32 | #include "aes192_dec.h" 33 | #include "keysize_descriptor.h" 34 | 35 | extern const bcdesc_t aes192_desc; 36 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal_aes256.c: -------------------------------------------------------------------------------- 1 | /* bcal_aes256.c */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file bcal_aes256.c 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2009-01-08 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | 28 | #include 29 | #include 30 | #include "blockcipher_descriptor.h" 31 | #include "aes.h" 32 | #include "aes256_enc.h" 33 | #include "aes256_dec.h" 34 | #include "aes_keyschedule.h" 35 | #include "keysize_descriptor.h" 36 | 37 | const char aes256_str[] PROGMEM = "AES-256"; 38 | 39 | const uint8_t aes256_keysize_desc[] PROGMEM = { KS_TYPE_LIST, 1, KS_INT(256), 40 | KS_TYPE_TERMINATOR }; 41 | 42 | const bcdesc_t aes256_desc PROGMEM = { 43 | BCDESC_TYPE_BLOCKCIPHER, 44 | BC_INIT_TYPE_1, 45 | aes256_str, 46 | sizeof(aes256_ctx_t), 47 | 128, 48 | {(void_fpt)aes256_init}, 49 | {(void_fpt)aes256_enc}, 50 | {(void_fpt)aes256_dec}, 51 | (bc_free_fpt)NULL, 52 | aes256_keysize_desc 53 | }; 54 | 55 | 56 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/bcal_aes256.h: -------------------------------------------------------------------------------- 1 | /* bcal_aes256.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file bcal_aes256.h 21 | * \email daniel.otte@rub.de 22 | * \author Daniel Otte 23 | * \date 2009-01-08 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | 28 | #include 29 | #include "blockcipher_descriptor.h" 30 | #include "aes.h" 31 | #include "aes256_enc.h" 32 | #include "aes256_dec.h" 33 | #include "keysize_descriptor.h" 34 | 35 | extern const bcdesc_t aes256_desc; 36 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/blockcipher_descriptor.h: -------------------------------------------------------------------------------- 1 | /* blockcipher_descriptor.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file blockcipher_descriptor.h 21 | * \author Daniel Otte 22 | * \date 2009-02-04 23 | * 24 | * \license GPLv3 or later 25 | * 26 | */ 27 | 28 | #ifndef BLOCKCIPHER_DESCRIPTOR_H_ 29 | #define BLOCKCIPHER_DESCRIPTOR_H_ 30 | #include 31 | #include 32 | 33 | 34 | #ifndef VOID_FPT 35 | #define VOID_FPT 36 | typedef void(*void_fpt)(void); 37 | #endif 38 | 39 | typedef void(*bc_init1_fpt)(void*, void*); 40 | typedef void(*bc_init2_fpt)(void*, uint16_t,void*); 41 | typedef void(*bc_enc1_fpt)(void*, void*); 42 | typedef void(*bc_enc2_fpt)(void*, void*, void*); 43 | typedef void(*bc_dec1_fpt)(void*, void*); 44 | typedef void(*bc_dec2_fpt)(void*, void*, void*); 45 | typedef void(*bc_free_fpt)(void*); 46 | 47 | typedef union{ 48 | void_fpt initvoid; 49 | bc_init1_fpt init1; 50 | bc_init2_fpt init2; 51 | } bc_init_fpt; 52 | 53 | typedef union{ 54 | void_fpt encvoid; 55 | bc_enc1_fpt enc1; 56 | bc_enc2_fpt enc2; 57 | } bc_enc_fpt; 58 | 59 | typedef union{ 60 | void_fpt decvoid; 61 | bc_dec1_fpt dec1; 62 | bc_dec2_fpt dec2; 63 | } bc_dec_fpt; 64 | 65 | #define BC_INIT_TYPE 0x01 66 | #define BC_INIT_TYPE_1 0x00 /* for fix keylength */ 67 | #define BC_INIT_TYPE_2 0x01 /* keylength is passed as second parameter */ 68 | 69 | #define BC_ENC_TYPE 0x02 70 | #define BC_ENC_TYPE_1 0x00 71 | #define BC_ENC_TYPE_2 0x02 72 | # 73 | #define BC_DEC_TYPE 0x04 74 | #define BC_DEC_TYPE_1 0x00 75 | #define BC_DEC_TYPE_2 0x04 76 | 77 | #define BCDESC_TYPE_BLOCKCIPHER 0x01 78 | 79 | typedef struct { 80 | uint8_t type; /* 1==blockcipher */ 81 | uint8_t flags; 82 | PGM_P name; 83 | uint16_t ctxsize_B; 84 | uint16_t blocksize_b; 85 | bc_init_fpt init; 86 | bc_enc_fpt enc; 87 | bc_dec_fpt dec; 88 | bc_free_fpt free; 89 | PGM_VOID_P valid_keysize_desc; 90 | } bcdesc_t; /* blockcipher descriptor type */ 91 | 92 | typedef struct{ 93 | bcdesc_t* desc_ptr; 94 | uint16_t keysize; 95 | void* ctx; 96 | } bcgen_ctx_t; 97 | 98 | #endif /* BLOCKCIPHER_DESCRIPTOR_H_ */ 99 | 100 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/gf256mul.S: -------------------------------------------------------------------------------- 1 | /* gf256mul.S */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | /* 21 | * File: gf256mul.S 22 | * Author: Daniel Otte 23 | * Date: 2008-12-19 24 | * License: GPLv3 or later 25 | * Description: peasant's algorithm for multiplication in GF(2^8) 26 | * 27 | */ 28 | 29 | #include 30 | #define OPTIMIZE_SMALL_A 31 | 32 | /* 33 | * param a: r24 34 | * param b: r22 35 | * param reducer: r20 36 | */ 37 | A = 23 38 | B = 22 39 | P = 24 40 | .global gf256mul 41 | 42 | #ifdef OPTIMIZE_SMALL_A 43 | gf256mul: 44 | mov A, r24 45 | clr r24 46 | 1: 47 | lsr A 48 | breq 4f 49 | brcc 2f 50 | eor P, B 51 | 2: 52 | lsl B 53 | brcc 3f 54 | eor B, r20 55 | 3: 56 | rjmp 1b 57 | 4: 58 | brcc 2f 59 | eor P, B 60 | 2: 61 | ret 62 | 63 | #else 64 | 65 | gf256mul: 66 | mov r21, r24 67 | clr r24 68 | ldi r25, 8 69 | 1: 70 | lsr A 71 | brcc 2f 72 | eor P, B 73 | 2: 74 | lsl B 75 | brcc 3f 76 | eor B, r20 77 | 3: 78 | dec r25 79 | brne 1b 80 | ret 81 | 82 | #endif 83 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/gf256mul.h: -------------------------------------------------------------------------------- 1 | /* gf256mul.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | #ifndef GF256MUL_H_ 20 | #define GF256MUL_H_ 21 | 22 | /** 23 | * \author Daniel Otte 24 | * \email daniel.otte@rub.de 25 | * \date 2008-12-19 26 | * \license GPLv3 27 | * \brief 28 | * 29 | * 30 | */ 31 | 32 | #include 33 | 34 | uint8_t gf256mul(uint8_t a, uint8_t b, uint8_t reducer); 35 | 36 | #endif /* GF256MUL_H_ */ 37 | 38 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/keysize_descriptor.h: -------------------------------------------------------------------------------- 1 | /* keysize_descriptor.h */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2009 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | /** 20 | * \file keysize_descriptor.h 21 | * \author Daniel Otte 22 | * \email daniel.otte@rub.de 23 | * \date 2009-01-07 24 | * \license GPLv3 or later 25 | */ 26 | 27 | #ifndef KEYSIZE_DESCRIPTOR_H_ 28 | #define KEYSIZE_DESCRIPTOR_H_ 29 | 30 | #include 31 | #include 32 | 33 | #define KS_TYPE_TERMINATOR 0x00 34 | #define KS_TYPE_LIST 0x01 35 | #define KS_TYPE_RANGE 0x02 36 | #define KS_TYPE_ARG_RANGE 0x03 37 | 38 | #define KS_INT(a) ((a)&0xFF), ((a)>>8) 39 | 40 | typedef struct{ /* keysize is valid if listed in items */ 41 | uint8_t n_items; /* number of items (value 0 is reserved) */ 42 | uint16_t items[]; /* list of valid lengths */ 43 | }keysize_desc_list_t; 44 | 45 | typedef struct{ /* keysize is valid if min<=keysize<=max */ 46 | uint16_t min; 47 | uint16_t max; 48 | }keysize_desc_range_t; 49 | 50 | typedef struct{ /* keysize is valid if min<=keysize<=max and if keysize mod distance == offset */ 51 | uint16_t min; 52 | uint16_t max; 53 | uint16_t distance; 54 | uint16_t offset; 55 | }keysize_desc_arg_range_t; 56 | 57 | uint8_t is_valid_keysize_P(PGM_VOID_P ks_desc, uint16_t keysize); 58 | uint16_t get_keysize(PGM_VOID_P ks_desc); 59 | uint16_t get_keysizes(PGM_VOID_P ks_desc, uint16_t** list); 60 | 61 | 62 | #endif /* KEYSIZE_DESCRIPTOR_H_ */ 63 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/memxor.S: -------------------------------------------------------------------------------- 1 | /* memxor.S */ 2 | /* 3 | This file is part of the AVR-Crypto-Lib. 4 | Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | /* 21 | * File: memxor.S 22 | * Author: Daniel Otte 23 | * Date: 2008-08-07 24 | * License: GPLv3 or later 25 | * Description: memxor, XORing one block into another 26 | * 27 | */ 28 | 29 | /* 30 | * void memxor(void* dest, const void* src, uint16_t n); 31 | */ 32 | /* 33 | * param dest is passed in r24:r25 34 | * param src is passed in r22:r23 35 | * param n is passed in r20:r21 36 | */ 37 | .global memxor 38 | memxor: 39 | movw r30, r24 40 | movw r26, r22 41 | movw r24, r20 42 | adiw r24, 0 43 | breq 2f 44 | 1: 45 | ld r20, X+ 46 | ld r21, Z 47 | eor r20, r21 48 | st Z+, r20 49 | sbiw r24, 1 50 | brne 1b 51 | 2: 52 | ret 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESLib-master/memxor.h: -------------------------------------------------------------------------------- 1 | #ifndef MEMXOR_H_ 2 | #define MEMXOR_H_ 3 | #include 4 | 5 | void memxor(void* dest, const void* src, uint16_t n); 6 | void memxor_P(void* dest, const void* src, uint16_t n); 7 | 8 | 9 | #endif 10 | -------------------------------------------------------------------------------- /Software/Chapter7Software/AESTest/AESTest.ino: -------------------------------------------------------------------------------- 1 | // 2 | // 3 | // AES Library Test 4 | // SwitchDoc Labs 5 | // February 2016 6 | // 7 | 8 | 9 | 10 | #include 11 | 12 | // 256 bit key for AES 13 | uint8_t key[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}; 14 | 15 | 16 | 17 | 18 | void setup() { 19 | 20 | Serial.begin(115200); 21 | 22 | 23 | 24 | 25 | 26 | 27 | } 28 | 29 | void loop() { 30 | // put your main code here, to run repeatedly: 31 | 32 | char data[] = "01234567890Hello"; 33 | 34 | 35 | int sizeOfArray; 36 | int i; 37 | 38 | sizeOfArray = sizeof(data) / sizeof(char); 39 | 40 | Serial.println(); 41 | 42 | Serial.print("data to be encrypted (ASCII format):\t "); 43 | Serial.println(data); 44 | 45 | Serial.print("data to be encrypted (Hex format):\t "); 46 | 47 | for (i = 0; i < sizeOfArray - 1; i++) 48 | { 49 | if (uint8_t(data[i]) < 0x10) 50 | Serial.print("0"); 51 | Serial.print(uint8_t(data[i]), HEX); 52 | 53 | } 54 | Serial.println(); 55 | 56 | 57 | // Now we encrypt the data using a 256 byte AES key 58 | 59 | aes256_enc_single(key, data); 60 | 61 | // print the encrypted data out in Hex 62 | 63 | Serial.print("encrypted (in Hex):\t\t\t "); 64 | 65 | 66 | for (i = 0; i < sizeOfArray - 1; i++) 67 | { 68 | if (uint8_t(data[i]) < 0x10) 69 | Serial.print("0"); 70 | Serial.print(uint8_t(data[i]), HEX); 71 | 72 | } 73 | Serial.println(); 74 | 75 | // Now decrypt the data and print it out 76 | 77 | aes256_dec_single(key, data); 78 | Serial.print("decrypted:\t\t\t\t "); 79 | Serial.println(data); 80 | } 81 | -------------------------------------------------------------------------------- /Software/Chapter7Software/Cryptosuite/README: -------------------------------------------------------------------------------- 1 | Cryptosuite is a cryptographic library for Arduino (including SHA and HMAC-SHA) 2 | 3 | It currently supports secure hashing and hashed message authentication using SHA-1, SHA-256, HMAC-SHA-1 and HMAC-SHA-256. 4 | 5 | Installation: 6 | Make a 'libraries' directory with your Arduino sketches folder if you do not already have one. 7 | Copy the 'Sha' directory into that directory. 8 | Restart Arduino to rescan for new libraries. 9 | 10 | Using SHA-1: 11 | #include "sha1.h" 12 | ... 13 | uint8_t *hash; 14 | Sha1.init(); 15 | Sha1.print("This is a message to hash"); 16 | hash = Sha1.result(); 17 | 18 | The hash result is then stored in hash[0], hash[1] .. hash[19]. 19 | 20 | Using HMAC-SHA-1: 21 | #include "sha1.h" 22 | ... 23 | uint8_t *hash; 24 | Sha1.initHmac("hash key",8); // key, and length of key in bytes 25 | Sha1.print("This is a message to hash"); 26 | hash = Sha1.resultHmac(); 27 | 28 | The hash result is then stored in hash[0], hash[1] .. hash[19]. 29 | 30 | Using SHA-256: 31 | #include "sha256.h" 32 | ... 33 | uint8_t *hash; 34 | Sha256.init(); 35 | Sha256.print("This is a message to hash"); 36 | hash = Sha256.result(); 37 | 38 | The hash result is then stored in hash[0], hash[1] .. hash[31]. 39 | 40 | Using HMAC-SHA-256: 41 | #include "sha256.h" 42 | ... 43 | uint8_t *hash; 44 | Sha256.initHmac("hash key",8); // key, and length of key in bytes 45 | Sha256.print("This is a message to hash"); 46 | hash = Sha256.resultHmac(); 47 | 48 | The hash result is then stored in hash[0], hash[1] .. hash[31]. 49 | 50 | 51 | Verification: 52 | The provided example code tests against published test vectors. 53 | SHA-1: FIPS 180-2, RFC3174 compliant 54 | HMAC-SHA-1: FIPS 198a compliant 55 | SHA-256: FIPS 180-2, RFC4231 compliant 56 | HMAC-SHA-256: RFC4231 compliant 57 | -------------------------------------------------------------------------------- /Software/Chapter7Software/Cryptosuite/Sha/examples/hmacsha256test/runtests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | jam u0 && expect test.ex 4 | -------------------------------------------------------------------------------- /Software/Chapter7Software/Cryptosuite/Sha/examples/hmacsha256test/test.ex: -------------------------------------------------------------------------------- 1 | #/usr/bin/expect 2 | 3 | set timeout 100 4 | spawn picocom -b 9600 /dev/ttyUSB0 5 | expect "+OK" 6 | -------------------------------------------------------------------------------- /Software/Chapter7Software/Cryptosuite/Sha/keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map For Cryptolib 3 | ####################################### 4 | 5 | ####################################### 6 | # Datatypes (KEYWORD1) 7 | ####################################### 8 | Sha1 KEYWORD1 9 | Sha256 KEYWORD1 10 | 11 | ####################################### 12 | # Methods and Functions (KEYWORD2) 13 | ####################################### 14 | 15 | init KEYWORD2 16 | initHmac KEYWORD2 17 | add KEYWORD2 18 | result KEYWORD2 19 | resultHmac KEYWORD2 20 | 21 | ####################################### 22 | # Constants (LITERAL1) 23 | ####################################### 24 | 25 | -------------------------------------------------------------------------------- /Software/Chapter7Software/Cryptosuite/Sha/readme.txt: -------------------------------------------------------------------------------- 1 | SHA implements secure hash functions that can be used for cryptography, data integrity and security purposes. 2 | 3 | Sha covers the following standards: 4 | SHA-1 (FIPS 180-2) 5 | SHA-256 (FIPS 180-2) 6 | HMAC-SHA-1 (FIPS 198a) 7 | HMAC-SHA-256 (FIPS 198a) 8 | 9 | What is a hash function? 10 | A hash function takes a message, and generates a number. 11 | A good hash function has the following properties: 12 | The number is large enough that you will never find two messages with the same number (a 'collision') 13 | It is computationally unfeasible to extract message information from its hash (without trying every possible combination) 14 | A small (1 bit) change in the message will produce a huge (approximately half of all bits) change in the hash. 15 | Fast to calculate 16 | 17 | SHA is slower than simple hashes (eg. parity), but has very high security - high enough to be used in currency transactions and confidential documents. 18 | SHA-1 is currently secure, but there is some suggestion it may not be for much longer. 19 | SHA-256 is slightly slower, but has higher security. 20 | 21 | What is an HMAC? 22 | HMACs are Hashed Message Authentication Codes. Using them, it is possible to prove that you have a secret key without actually disclosing it. 23 | -------------------------------------------------------------------------------- /Software/Chapter7Software/Cryptosuite/Sha/sha1.h: -------------------------------------------------------------------------------- 1 | #ifndef Sha1_h 2 | #define Sha1_h 3 | 4 | #include 5 | #include "Print.h" 6 | 7 | #if ARDUINO < 100 8 | #define __WRITE_RESULT void 9 | #define __WRITE_RETURN(x) return; 10 | #else 11 | #define __WRITE_RESULT size_t 12 | #define __WRITE_RETURN(x) return x; 13 | #endif 14 | 15 | #define HASH_LENGTH 20 16 | #define BLOCK_LENGTH 64 17 | 18 | union _buffer { 19 | uint8_t b[BLOCK_LENGTH]; 20 | uint32_t w[BLOCK_LENGTH/4]; 21 | }; 22 | union _state { 23 | uint8_t b[HASH_LENGTH]; 24 | uint32_t w[HASH_LENGTH/4]; 25 | }; 26 | 27 | class Sha1Class : public Print 28 | { 29 | public: 30 | void init(void); 31 | void initHmac(const uint8_t* secret, int secretLength); 32 | uint8_t* result(void); 33 | uint8_t* resultHmac(void); 34 | virtual __WRITE_RESULT write(uint8_t); 35 | using Print::write; 36 | private: 37 | void pad(); 38 | void addUncounted(uint8_t data); 39 | void hashBlock(); 40 | uint32_t rol32(uint32_t number, uint8_t bits); 41 | _buffer buffer; 42 | uint8_t bufferOffset; 43 | _state state; 44 | uint32_t byteCount; 45 | uint8_t keyBuffer[BLOCK_LENGTH]; 46 | uint8_t innerHash[HASH_LENGTH]; 47 | 48 | }; 49 | extern Sha1Class Sha1; 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /Software/Chapter7Software/Cryptosuite/Sha/sha256.h: -------------------------------------------------------------------------------- 1 | #ifndef Sha256_h 2 | #define Sha256_h 3 | 4 | #include 5 | #include "Print.h" 6 | 7 | #if ARDUINO < 100 8 | #define __WRITE_RESULT void 9 | #define __WRITE_RETURN(x) return; 10 | #else 11 | #define __WRITE_RESULT size_t 12 | #define __WRITE_RETURN(x) return x; 13 | #endif 14 | 15 | #define HASH_LENGTH 32 16 | #define BLOCK_LENGTH 64 17 | 18 | union _buffer { 19 | uint8_t b[BLOCK_LENGTH]; 20 | uint32_t w[BLOCK_LENGTH/4]; 21 | }; 22 | union _state { 23 | uint8_t b[HASH_LENGTH]; 24 | uint32_t w[HASH_LENGTH/4]; 25 | }; 26 | 27 | class Sha256Class : public Print 28 | { 29 | public: 30 | void init(void); 31 | void initHmac(const uint8_t* secret, int secretLength); 32 | uint8_t* result(void); 33 | uint8_t* resultHmac(void); 34 | virtual __WRITE_RESULT write(uint8_t); 35 | using Print::write; 36 | private: 37 | void pad(); 38 | void addUncounted(uint8_t data); 39 | void hashBlock(); 40 | uint32_t ror32(uint32_t number, uint8_t bits); 41 | _buffer buffer; 42 | uint8_t bufferOffset; 43 | _state state; 44 | uint32_t byteCount; 45 | uint8_t keyBuffer[BLOCK_LENGTH]; 46 | uint8_t innerHash[HASH_LENGTH]; 47 | }; 48 | extern Sha256Class Sha256; 49 | 50 | #endif 51 | -------------------------------------------------------------------------------- /Software/Chapter7Software/sha256test/sha256.h: -------------------------------------------------------------------------------- 1 | #ifndef Sha256_h 2 | #define Sha256_h 3 | 4 | #include 5 | #include "Print.h" 6 | 7 | #if ARDUINO < 100 8 | #define __WRITE_RESULT void 9 | #define __WRITE_RETURN(x) return; 10 | #else 11 | #define __WRITE_RESULT size_t 12 | #define __WRITE_RETURN(x) return x; 13 | #endif 14 | 15 | #define HASH_LENGTH 32 16 | #define BLOCK_LENGTH 64 17 | 18 | union _buffer { 19 | uint8_t b[BLOCK_LENGTH]; 20 | uint32_t w[BLOCK_LENGTH/4]; 21 | }; 22 | union _state { 23 | uint8_t b[HASH_LENGTH]; 24 | uint32_t w[HASH_LENGTH/4]; 25 | }; 26 | 27 | class Sha256Class : public Print 28 | { 29 | public: 30 | void init(void); 31 | void initHmac(const uint8_t* secret, int secretLength); 32 | uint8_t* result(void); 33 | uint8_t* resultHmac(void); 34 | virtual __WRITE_RESULT write(uint8_t); 35 | using Print::write; 36 | private: 37 | void pad(); 38 | void addUncounted(uint8_t data); 39 | void hashBlock(); 40 | uint32_t ror32(uint32_t number, uint8_t bits); 41 | _buffer buffer; 42 | uint8_t bufferOffset; 43 | _state state; 44 | uint32_t byteCount; 45 | uint8_t keyBuffer[BLOCK_LENGTH]; 46 | uint8_t innerHash[HASH_LENGTH]; 47 | }; 48 | extern Sha256Class Sha256; 49 | 50 | #endif 51 | -------------------------------------------------------------------------------- /Software/Chapter7Software/sha256test/sha256test.ino: -------------------------------------------------------------------------------- 1 | // 2 | // SHA256 Hash Test 3 | // 4 | // For both the Arduino and ESP8266 5 | // SwitchDoc Labs 6 | // 7 | // February 2016 8 | 9 | #include "sha256.h" 10 | 11 | 12 | 13 | void printHash(uint8_t* hash) { 14 | int i; 15 | for (i = 0; i < 32; i++) { 16 | Serial.print("0123456789abcdef"[hash[i] >> 4]); 17 | Serial.print("0123456789abcdef"[hash[i] & 0xf]); 18 | } 19 | Serial.println(); 20 | } 21 | 22 | 23 | 24 | void setup() { 25 | 26 | 27 | Serial.begin(115200); 28 | Serial.println("SHA256 Hash Test"); 29 | Serial.println(); 30 | 31 | } 32 | 33 | void loop() { 34 | 35 | uint8_t *hash; 36 | Sha256.init(); 37 | String hashMessage; 38 | int i; 39 | 40 | i = 0; 41 | 42 | while (1) 43 | { 44 | 45 | hashMessage = "This is a message to hash-"; 46 | hashMessage = hashMessage + String(i % 10); 47 | Serial.print("Hashing Message: "); 48 | Serial.println(hashMessage); 49 | Sha256.print(hashMessage); 50 | 51 | hash = Sha256.result(); 52 | 53 | printHash(hash); 54 | Serial.println(); 55 | delay(5000); 56 | 57 | i++; 58 | 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! --------------------------------------------------------------------------------