-
Notifications
You must be signed in to change notification settings - Fork 0
/
JunairApp.py
254 lines (211 loc) · 10.9 KB
/
JunairApp.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#to allow time to stop the program autorun if necessary
import time
#This is the library for communicating with the IOT hub on Azure
from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult
from iothub_client import IoTHubMessage, IoTHubMessageDispositionResult, IoTHubError, DeviceMethodReturnValue
import RPi.GPIO as GPIO
import sys,re
import math
import numpy as np
from datetime import date
from Hologram.HologramCloud import HologramCloud
#import the telemetry class which allows communication with iothubclient
from telemetry import Telemetry
#import the sensor read functions from sensors.py
from sensors import *
#import status checking functions
from error_status import *
#import MCP3008 (ADC) Library
import Adafruit_MCP3008
#importing the DHT11 sensor library
import Adafruit_DHT
#Import the firmware code for the Adafruit MAX31855 Amplifier for the Thermocouple
import Adafruit_MAX31855.MAX31855 as MAX31855
#Setting the variable for the max length of the arrays storing data
MAX_ARRAY_LENGTH = 50
dutyCycleArray = []
#creating DHT sensor object
DHTsensor = Adafruit_DHT.DHT22
#Configuring SPI Software for the Adafruit_MCP3008 ADC. These are the GPIO numbers
mcp = Adafruit_MCP3008.MCP3008(clk=22, cs=25, miso=23, mosi=24)
#configuring the SPI software for the MAX31855 Amplifier for the Thermocouple CLK=21, CS=20, DO=16
max_sensor = MAX31855.MAX31855(21, 20, 16)
#configure pin for Adafruit_DHT11 Sensor
DHTpin = 18
#pin number for LED
LED_PIN_ADDRESS = 27
#Making a telemetry object which will allow this computer to communicate with IotHub
telemetry = Telemetry()
#instantiating cellular connection
hologram = HologramCloud(dict(), network='cellular')
result = hologram.network.connect()
MESSAGE_COUNT = 0
MESSAGE_SWITCH = True
# global counters
RECEIVE_CALLBACKS = 0
SEND_CALLBACKS = 0
RECEIVE_CONTEXT = 0
SEND_REPORTED_STATE_CALLBACKS = 0
#set the connection string variable as the 2nd parameter that was passed into the application call (i.e. "python app.py [connection string]"")
CONNECTION_STRING = 'HostName=JA-TestProject.azure-devices.net;DeviceId=RasBerryOnlineTestBoard;SharedAccessKey=56PL8iS1Pb2i5SE2Qke8CXXIRLgmCwJVHL+CLauuW1o='
#Using the MQTT protocol for sending messages.
#It is a lightweight messaging protocol for small devices and sensors
PROTOCOL = IoTHubTransportProvider.MQTT
#Set the mode for the raspberry pi to use the pin number (GPIO.BCM). also setting the output pin for the LED
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN_ADDRESS, GPIO.OUT)
GPIO.output(LED_PIN_ADDRESS,GPIO.HIGH)
#this is the message text variable that gets sent to the IOT hub after being formatted with the respective variables
MSG_TXT = "{\"deviceId\": \"JunAir 1.0\",\"timeEpoch\": %i,\"dutyCycle\": %i,\"compState\": %i ,\"thermocoupleTemperature\": %f,\"transducerPressure\": %f,\"am2302Temperature\": %f,\"am2302Humidity\": %f,\"sht20Humidity\": %f,\"sht20Temperature\": %f,\"compAmps\": %f,\"statusString\": %s,\"sensorString\": %s}"
#not too sure about this method yet. I think it recieves data from the IOT hub as a confirmation that the data was recieved
def receive_message_callback(message, counter):
global RECEIVE_CALLBACKS
message_buffer = message.get_bytearray()
size = len(message_buffer)
map_properties = message.properties()
key_value_pair = map_properties.get_internals()
counter += 1
RECEIVE_CALLBACKS += 1
return IoTHubMessageDispositionResult.ACCEPTED
#Simple method for sending text to the terminal signifying that a confirmation was recieved with the data passed into it
def send_reported_state_callback(status_code, user_context):
global SEND_REPORTED_STATE_CALLBACKS
SEND_REPORTED_STATE_CALLBACKS += 1
#This is the function that send that information back to the terminal that the app is being run from. The led blinks every time that this method is called
# and completed successfully.
def send_confirmation_callback(message, result, user_context):
global SEND_CALLBACKS
map_properties = message.properties()
key_value_pair = map_properties.get_internals()
SEND_CALLBACKS += 1
led_blink()
def iothub_client_init(CONNECTION_STRING_GIVEN, PROTOCOL):
#prepare the iothub client (basically the iot hub on azure)
client = IoTHubClient(CONNECTION_STRING_GIVEN,PROTOCOL)
client.set_option("product_info", "HappyPath_RaspberryPi-Python")
client.set_option("Message Time Out", 10000 )
if client.protocol == IoTHubTransportProvider.MQTT:
client.set_option("logtrace",0)
client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
return client
def print_last_message_time(client):
try:
last_message = client.get_last_message_receive_time()
except IoTHubClientError as iothub_client_error:
if iothub_client_error.args[0].result == IoTHubClientResult.INDEFINITE_TIME:
print ( "No message received" )
else:
print ( iothub_client_error )
def iothub_client_sample_run():
led_blink()
global compRunning
global globalTimeOn
global dutyCycleArray
global am2302HumidityArray
try:
client = iothub_client_init(CONNECTION_STRING, PROTOCOL)
if client.protocol == IoTHubTransportProvider.MQTT:
reported_state = "{\"newState\":\"standBy\"}"
client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, 0)
#client_junair.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, 0)
telemetry.send_telemetry_data(parse_iot_hub_name,"success", "The connection to the IOT Hub has been established!!!...Boom")
while True:
global MESSAGE_COUNT, MESSAGE_SWITCH
if MESSAGE_SWITCH:
print ( "IoTHubClient sending %d messages...boom" % MESSAGE_COUNT )
#reading data from sensors and formatting messages to be sent to client(iotHub)
timeEpoch = int(time.time())
#Read data from thermocouple and make sure it is not null
thermocoupleTemperature = round(max_sensor.readTempC(),3)
if thermocoupleTemperature is None or np.isnan(thermocoupleTemperature) or not max_sensor.readTempC() or thermocoupleTemperature == 0:
thermocoupleTemperature = 0.002
#read data from am2302 sensor
am2302Humidity,am2302Temperature = Adafruit_DHT.read_retry(DHTsensor,DHTpin)
if am2302Humidity is None:
am2302Humidity, am2302Temperature = [0.002,0.002]
#read data from the pressure sensor
transducerPressure=round((mcp.read_adc(3)-73)*150.0/595.2,3)
if transducerPressure <-1:
transducerPressure = 0.002
#check compressor state and amps usage
compAmps = checkAmpUsage()
compState = checkCompressorState()
if compAmps is None:
compAmps = 0.002
compState = 0.002
#read data from sht20 sensor
try:
sht20Humidity = GetShtHumid()
except:
sht20Humidity = 0.002
try:
sht20Temperature = GetShtTemp_c()
except:
sht20Temperature = 0.002
#storing data into csv files
storerCSV("sht20Humidity.csv", sht20Humidity, 'a')
storerCSV("sht20Temperature.csv", sht20Temperature, 'a')
storerCSV("thermocouple.csv", thermocoupleTemperature, 'a')
storerCSV("am2302Humidity.csv", am2302Humidity, 'a')
storerCSV("am2302Temperature.csv", am2302Temperature, 'a')
storerCSV("pressure.csv", transducerPressure, 'a')
storerCSV("current.csv", compAmps, 'a')
#Check Duty Cycle
dutyCycleArray.append(compState)
if len(dutyCycleArray) > 200:
dutyCycleArray = dutyCycleArray[1:150]
try:
dutyCycle = calculateDutyCycle()
if dutyCycle is None:
dutyCyle = 0.002
except:
dutyCycle = 0.002
statusString, sensorString = readerStatusCSV()
print(date.today())
msg_text_formatted = MSG_TXT %(timeEpoch,dutyCycle,compState,thermocoupleTemperature,transducerPressure,am2302Temperature,am2302Humidity,sht20Humidity,sht20Temperature,compAmps,statusString,sensorString)
print(msg_text_formatted)
message = IoTHubMessage(msg_text_formatted)
# optional: assign ids
message.message_id = "message_%d" % MESSAGE_COUNT
message.correlation_id = "correlation_%d" % MESSAGE_COUNT
#mapping extra properties for the message. basically just adding a temperature warning
prop_map = message.properties()
prop_map.add("TemperatureAlert... ","true" if thermocoupleTemperature > 90.0 else "false")
#sending the message to the terminal from iotHub
client.send_event_async(message,send_confirmation_callback,MESSAGE_COUNT)
print(sys.getsizeof(message))
print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT )
#sending the send status to the terminal from the iotHub
status = client.get_send_status()
print("Send status is... %s" % status)
MESSAGE_COUNT +=1
time.sleep(2)
except IoTHubError as iothub_error:
print ( "Unexpected error %s from IoTHub" % iothub_error )
telemetry.send_telemetry_data(parse_iot_hub_name(), "failed", "Unexpected error %s from IoTHub" % iothub_error)
return
except KeyboardInterrupt:
print ( "IoTHubClient sample stopped" )
print(globalTimeOn)
return
#Calculating the duty cycle of the compressor
def calculateDutyCycle():
global dutyCycleArray
y = np.array(dutyCycleArray)
num_ones = (y == 1).sum()
return round((float(num_ones)/len(y)),3)
#method to get the LED to blink for a specified amount of time
def led_blink():
global compRunning
global globalTimeOn
GPIO.output(LED_PIN_ADDRESS,GPIO.HIGH)
time.sleep(1) #the time that the LED stays lit for
GPIO.output(LED_PIN_ADDRESS, GPIO.LOW)
#self explanatory method
def parse_iot_hub_name():
m = re.search("HostName=(.*?)\.", CONNECTION_STRING)
return m.group(1)
if __name__ == "__main__":
print("\nPython %s" % sys.version)
print(" IoT Hub Client for Python")
iothub_client_sample_run()