Skip to content

Commit 553b101

Browse files
authored
Merge pull request #78 from CleoQc/feature/Scratch_THP_sensor
support THP sensor in Scratch
2 parents 0397238 + 8a4d93a commit 553b101

File tree

2 files changed

+119
-32
lines changed

2 files changed

+119
-32
lines changed

Scratch/diSensorsScratch.py

Lines changed: 119 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,29 @@
55
import time
66
import re
77
import sys
8+
import logging
9+
10+
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
11+
dilogger = logging.getLogger("Sensors")
812

913
try:
1014
from di_sensors import easy_light_color_sensor
1115
except:
12-
print("Cannot find light_color_sensor library")
16+
dilogger.debug("Cannot find light_color_sensor library")
1317

1418
try:
1519
from di_sensors import easy_line_follower
1620
except:
17-
print("Cannot find easy_line_follower library")
21+
dilogger.debug("Cannot find easy_line_follower library")
22+
23+
try:
24+
from di_sensors import easy_temp_hum_press
25+
except:
26+
dilogger.debug("Cannot find easy_temp_hum_press library")
1827

19-
en_debug = 1
2028
scratch_lightcolor = None
2129
scratch_linefollower = None
30+
scratch_thp = None
2231

2332

2433
# LIGHT COLOR SENSOR
@@ -37,31 +46,69 @@
3746
# LINE FOLLOWER SENSOR
3847
regexlinefollower = "(^\s*(i2c)?\s*(line)\s*$)"
3948

49+
# THP SENSOR
50+
regexthp = "(^\s*(i2c)?\s*(temp)|(pressure)|(humidity)|(thp)\s*$)"
51+
4052
# ALL SENSORS
41-
regexdisensors = "("+ regexlightcolor+")|(" + regexlinefollower + ")"
53+
regexdisensors = "(" + \
54+
regexlightcolor + ")|(" + \
55+
regexlinefollower + ")|(" + \
56+
regexthp + ")"
57+
4258
compiled_disensors = re.compile(regexdisensors, re.IGNORECASE)
4359

4460
def detect_light_color_sensor():
4561
global scratch_lightcolor
4662
try:
4763
# setting led_state to True just to give feedback to the user.
4864
scratch_lightcolor = easy_light_color_sensor.EasyLightColorSensor(led_state = True)
49-
print("Light Color Sensor is detected")
65+
dilogger.info("Light Color Sensor is detected")
66+
try:
67+
''' attempt to broadcast commands'''
68+
s.broadcast('color')
69+
s.broadcast('rgb')
70+
s.broadcast('light')
71+
except:
72+
''' no big deal at this stage '''
73+
pass
5074
except:
51-
pass
75+
dilogger.debug("Light Color Sensor not found")
5276

5377
def detect_line_follower():
5478
# force line follower to I2C port for now
5579
global scratch_linefollower
5680
try:
5781
scratch_linefollower = easy_line_follower.EasyLineFollower()
58-
print("Line Follower is detected")
82+
dilogger.info("Line Follower is detected")
83+
try:
84+
s.broadcast('line')
85+
except:
86+
pass
5987
except:
88+
dilogger.debug("Line Follower not found")
89+
90+
def detect_thp():
91+
# force THP sensor to I2C port for now
92+
global scratch_thp
93+
try:
94+
scratch_thp = easy_temp_hum_press.EasyTHPSensor()
95+
dilogger.info("THP is detected")
96+
try:
97+
s.broadcast('temp')
98+
s.broadcast('humidity')
99+
s.broadcast('pressure')
100+
s.broadcast('thp')
101+
except:
102+
pass
103+
except Exception as e:
104+
dilogger.debug("THP not found")
105+
dilogger.debug(e)
60106
pass
61107

62108
def detect_all():
63109
detect_light_color_sensor()
64110
detect_line_follower()
111+
detect_thp()
65112

66113
def isDiSensorsMsg(msg):
67114
'''
@@ -84,35 +131,41 @@ def handleDiSensors(msg):
84131
Use regex to validate it and take it apart
85132
'''
86133
global scratch_lightcolor
87-
if en_debug:
88-
print ("handleDiSensors Rx: {}".format(msg))
134+
dilogger.debug ("handleDiSensors Rx: {}".format(msg))
89135

90136
retdict = {}
91137

92138
regObj = compiled_disensors.match(msg)
93139
if regObj == None:
94-
print ("DI Sensors: Command %s is not recognized" % (msg))
140+
dilogger.info ("DI Sensors: Command %s is not recognized" % (msg))
95141
return None
96-
# else:
97-
# if en_debug:
98-
# print ("matching done")
142+
else:
143+
dilogger.debug ("matching done")
99144

100145
if regObj:
101-
# print (regObj.groups())
146+
dilogger.debug (regObj.groups())
102147

103148
# handling a light color sensor
104149
port = regObj.group(1) # port nb goes from 0 to 3 from now on
105-
# print("Port is %s" % port)
150+
dilogger.debug("Port is %s" % port)
106151

107152
# which method of the light color sensor is requested
108153
color_cmd = regObj.group(4)
109154
rgb_cmd = regObj.group(5)
110155
light_cmd = regObj.group(6)
111156
line_cmd = regObj.group(7)
157+
temp_cmd = regObj.group(14)
158+
pressure_cmd = regObj.group(15)
159+
humidity_cmd = regObj.group(16)
160+
thp_cmd = regObj.group(17)
161+
162+
# don't use logger here as many of the arguments are None
163+
# and it crashes the logger
112164
print(color_cmd, rgb_cmd, light_cmd, line_cmd)
165+
print(temp_cmd, pressure_cmd, humidity_cmd, thp_cmd)
113166

114167
else:
115-
print( "DI Sensors: unknown regex error ")
168+
dilogger.info( "DI Sensors: unknown regex error ")
116169
return None
117170

118171
retdict = {}
@@ -122,7 +175,7 @@ def handleDiSensors(msg):
122175
if scratch_lightcolor == None:
123176
detect_light_color_sensor()
124177
if scratch_lightcolor != None:
125-
# print("Query color command")
178+
dilogger.debug("Query color command")
126179
try:
127180
scratch_lightcolor.set_led(True)
128181
color = scratch_lightcolor.safe_raw_colors()
@@ -135,7 +188,7 @@ def handleDiSensors(msg):
135188
scratch_lightcolor = None
136189
retdict["color status"] = "sensor not found"
137190
except Exception as e:
138-
print("color_cmd failed: ",e)
191+
dilogger.info("color_cmd failed: ",e)
139192
retdict["color"] = "unknown"
140193
scratch_lightcolor = None
141194
retdict["color status"] = "sensor not found"
@@ -148,18 +201,18 @@ def handleDiSensors(msg):
148201
if scratch_lightcolor == None:
149202
detect_light_color_sensor()
150203
if scratch_lightcolor != None:
151-
# print ("Query rgb values")
204+
dilogger.debug ("Query rgb values")
152205
try:
153206
red, green, blue = scratch_lightcolor.safe_rgb()
154207
if red != -1 and green != -1 and blue != -1:
155208
retdict["rgb status"] = "ok"
156209
except Exception as e:
157-
print("rgb_cmd failed: ",e)
210+
dilogger.info("rgb_cmd failed ")
211+
dilogger.info(str(e))
158212
red, green, blue = [-1,-1,-1]
159213
scratch_lightcolor = None
160214
retdict["rgb status"] = "sensor not found"
161215

162-
# print(red, green, blue)
163216
retdict["rgb red"] = red
164217
retdict["rgb green"] = green
165218
retdict["rgb blue"] = blue
@@ -172,7 +225,7 @@ def handleDiSensors(msg):
172225
detect_light_color_sensor()
173226
if scratch_lightcolor != None:
174227
try:
175-
# print("Query light value")
228+
dilogger.debug("Query light value")
176229
scratch_lightcolor.set_led(False, True)
177230
time.sleep(0.01)
178231
_,_,_,a = scratch_lightcolor.safe_raw_colors()
@@ -186,14 +239,14 @@ def handleDiSensors(msg):
186239
scratch_lightcolor = None
187240
retdict["light status"] = "sensor not found"
188241
except Exception as e:
189-
print("light_cmd failed: ", e)
242+
dilogger.info("light_cmd failed: " + str(e) )
190243
scratch_lightcolor = None
191244
retdict["light status"] = "sensor not found"
192245
else:
193246
retdict["light status"] = "sensor not found"
194247

195248
elif line_cmd != None:
196-
# print("Found line follower cmd")
249+
dilogger.debug("Found line follower cmd")
197250
if not scratch_linefollower:
198251
detect_line_follower()
199252

@@ -215,10 +268,44 @@ def handleDiSensors(msg):
215268
else:
216269
retdict["line status"] = "Oops! Could not find the line follower"
217270
except Exception as e:
218-
retdict["line status"] = "Oops! Could not read the line follower: " + str(e)
271+
retdict["line status"] = "Oops! Could not read the line follower"
272+
dilogger.info(str(e) )
273+
274+
elif thp_cmd or temp_cmd or pressure_cmd or humidity_cmd:
275+
''' any THP cmd '''
276+
try:
277+
if not scratch_thp:
278+
detect_thp()
279+
if temp_cmd or thp_cmd :
280+
''' temperature sensor'''
281+
dilogger.debug("temperature sensor")
282+
retdict["temperature (C)"] = scratch_thp.safe_celsius()
283+
retdict["temperature (F)"] = scratch_thp.safe_fahrenheit()
284+
285+
if pressure_cmd or thp_cmd:
286+
''' pressure sensor '''
287+
retdict["pressure (Pa)"] = scratch_thp.safe_pressure()
288+
289+
if humidity_cmd or thp_cmd:
290+
''' humidity sensor '''
291+
retdict["humidity (%)"] = scratch_thp.safe_humidity()
292+
293+
retdict["THP Status"] = "ok"
294+
295+
except Exception as e:
296+
retdict["THP Status"] = "Oops! Could not read the THP sensor"
297+
dilogger.info(str(e))
219298

220299
return (retdict)
221300

301+
def broadcast(in_str):
302+
global s
303+
if s == None:
304+
s = scratch.Scratch()
305+
try:
306+
s.broadcast(in_str)
307+
except:
308+
dilogger.debug("failed broadcasting")
222309

223310
# this is used when developing.
224311
# the light color sensor is not supported as a standalone in Scratch
@@ -239,6 +326,7 @@ def handleDiSensors(msg):
239326
print ("DI Sensors Scratch: Connected to Scratch successfully")
240327
connected = 1 # We are succesfully connected! Exit Away!
241328
# time.sleep(1)
329+
detect_all()
242330

243331
except scratch.ScratchError:
244332
arbitrary_delay = 10 # no need to issue error statement if at least 10 seconds haven't gone by.
@@ -259,8 +347,7 @@ def handleDiSensors(msg):
259347
m = s.receive()
260348

261349
msg = m[1]
262-
if en_debug:
263-
print("Rx:{}".format(msg))
350+
dilogger.debug("Rx:{}".format(msg))
264351

265352
if isDiSensorsMsg(msg):
266353
sensors = handleDiSensors(msg)
@@ -269,19 +356,19 @@ def handleDiSensors(msg):
269356

270357
except KeyboardInterrupt:
271358
running= False
272-
print ("DI Sensors Scratch: Disconnected from Scratch")
359+
dilogger.info ("DI Sensors Scratch: Disconnected from Scratch")
273360
break
274361
except (scratch.scratch.ScratchConnectionError,NameError) as e:
275362
while True:
276363
#thread1.join(0)
277-
print ("DI Sensors Scratch: Scratch connection error, Retrying")
364+
dilogger.info ("DI Sensors Scratch: Scratch connection error, Retrying")
278365
time.sleep(5)
279366
try:
280367
s = scratch.Scratch()
281368
s.broadcast('READY')
282-
print ("DI Sensors Scratch: Connected to Scratch successfully")
369+
dilogger.info ("DI Sensors Scratch: Connected to Scratch successfully")
283370
break
284371
except scratch.ScratchError:
285-
print ("DI Sensors Scratch: Scratch is either not opened or remote sensor connections aren't enabled\n..............................\n")
372+
dilogger.info ("DI Sensors Scratch: Scratch is either not opened or remote sensor connections aren't enabled\n..............................\n")
286373
except Exception as e:
287-
print ("DI Sensors Scratch: Error %s" % e )
374+
dilogger.info ("DI Sensors Scratch: Error %s" % e )

Scratch/di_sensorscommands.png

188 KB
Loading

0 commit comments

Comments
 (0)