-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathWippersnapper.cpp
More file actions
2923 lines (2676 loc) · 110 KB
/
Wippersnapper.cpp
File metadata and controls
2923 lines (2676 loc) · 110 KB
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* @file Wippersnapper.cpp
*
* @mainpage Adafruit Wippersnapper Wrapper
*
* @section intro_sec Introduction
*
* This is the documentation for Adafruit's Wippersnapper wrapper for the
* Arduino platform. It is designed specifically to work with the
* Adafruit IO+ Wippersnapper IoT platform.
*
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* @section dependencies Dependencies
*
* This library depends on <a
* href="https://github.com/adafruit/Adafruit_Sensor"> Adafruit_Sensor</a> being
* present on your system. Please make sure you have installed the latest
* version before using this library.
*
* @section author Author
*
* Copyright (c) Brent Rubell 2020-2023 for Adafruit Industries.
*
* @section license License
*
* BSD license, all text here must be included in any redistribution.
*
*/
#include "Wippersnapper.h"
#include "Wippersnapper_Networking.h"
// Define the global WS instance as the platform-specific derived class
// This ensures virtual methods like _connect() route to the correct implementation
Wippersnapper_WiFi WS;
Wippersnapper::Wippersnapper() {
_mqtt = 0; // MQTT Client object
// Reserved MQTT Topics
_topic_description = 0;
_topic_description_status = 0;
_topic_signal_device = 0;
_topic_signal_brkr = 0;
_err_topic = 0;
_throttle_topic = 0;
_err_sub = 0;
_throttle_sub = 0;
// Init. component classes
// LEDC (ESP32-ONLY)
#ifdef ARDUINO_ARCH_ESP32
WS._ledc = new ws_ledc();
#endif
// PWM (Arch-specific implementations)
#ifdef ARDUINO_ARCH_ESP32
WS._pwmComponent = new ws_pwm(WS._ledc);
#else
WS._pwmComponent = new ws_pwm();
#endif
// Servo
WS._servoComponent = new ws_servo();
// UART
WS._uartComponent = new ws_uart();
// DallasSemi (OneWire)
WS._ds18x20Component = new ws_ds18x20();
// Display controller
WS._displayController = new DisplayController();
};
/**************************************************************************/
/*!
@brief Wippersnapper destructor
*/
/**************************************************************************/
Wippersnapper::~Wippersnapper() {
// free topics
free(_topic_description);
free(_topic_signal_device);
free(_topic_signal_brkr);
free(_err_sub);
free(_throttle_sub);
}
/**************************************************************************/
/*!
@brief Provisions a WipperSnapper device with its network
configuration and Adafruit IO credentials.
*/
/**************************************************************************/
void Wippersnapper::provision() {
// Obtain device's MAC address
getMacAddr();
// Initialize the status LED for signaling FS errors
initStatusLED();
// Initialize the filesystem
#ifdef USE_TINYUSB
_fileSystem = new Wippersnapper_FS();
#elif defined(USE_LITTLEFS)
_littleFS = new WipperSnapper_LittleFS();
#endif
// Parse secrets.json file
#ifdef USE_TINYUSB
_fileSystem->parseSecrets();
#elif defined(USE_LITTLEFS)
_littleFS->parseSecrets();
#else
set_user_key(); // non-fs-backed, sets global credentials within network iface
#endif
// Set the status pixel's brightness
setStatusLEDBrightness(WS._config.status_pixel_brightness);
// Set device's wireless credentials
set_ssid_pass();
}
/**************************************************************************/
/*!
@brief Disconnects from Adafruit IO+ Wippersnapper.
*/
/**************************************************************************/
void Wippersnapper::disconnect() { _disconnect(); }
// Concrete class definition for abstract classes
/****************************************************************************/
/*!
@brief Connects to wireless network.
*/
/****************************************************************************/
void Wippersnapper::_connect() {
WS_DEBUG_PRINTLN("ERROR: Please define a network interface!");
}
/****************************************************************************/
/*!
@brief Disconnect Wippersnapper MQTT session and network.
*/
/****************************************************************************/
void Wippersnapper::_disconnect() {
WS_DEBUG_PRINTLN("ERROR: Please define a network interface!");
}
/****************************************************************************/
/*!
@brief Sets the network interface's unique identifier, typically the
MAC address.
*/
/****************************************************************************/
void Wippersnapper::getMacAddr() {
WS_DEBUG_PRINTLN("ERROR: Please define a network interface!");
}
/****************************************************************************/
/*!
@brief Gets the network's RSSI.
@return int32_t RSSI value, 0 to 255, in dB
*/
/****************************************************************************/
int32_t Wippersnapper::getRSSI() {
WS_DEBUG_PRINTLN("ERROR: Please define a network interface!");
return 0;
}
/****************************************************************************/
/*!
@brief Sets up the MQTT client session.
@param clientID
A unique client identifier string.
*/
/****************************************************************************/
void Wippersnapper::setupMQTTClient(const char * /*clientID*/) {
WS_DEBUG_PRINTLN("ERROR: Please define a network interface!");
}
/****************************************************************************/
/*!
@brief Returns the network's connection status
@returns Network status as ws_status_t.
*/
/****************************************************************************/
ws_status_t Wippersnapper::networkStatus() {
WS_DEBUG_PRINTLN("ERROR: Please define a network interface!");
return WS_IDLE;
}
/****************************************************************************/
/*!
@brief Sets the device's wireless network credentials.
@param ssid
Your wireless network's SSID
@param ssidPassword
Your wireless network's password.
*/
/****************************************************************************/
void Wippersnapper::set_ssid_pass(const char * /*ssid*/,
const char * /*ssidPassword*/) {
WS_DEBUG_PRINTLN("ERROR: Please define a network interface!");
}
/****************************************************************************/
/*!
@brief Sets the device's wireless network credentials from the
secrets.json configuration file.
*/
/****************************************************************************/
void Wippersnapper::set_ssid_pass() {
WS_DEBUG_PRINTLN("ERROR: Please define a network interface!");
}
/***********************************************************/
/*!
@brief Performs a scan of local WiFi networks.
@returns True if `_network_ssid` is found, False otherwise.
*/
/***********************************************************/
bool Wippersnapper::check_valid_ssid() {
WS_DEBUG_PRINTLN("ERROR: Please define a network interface!");
return false;
}
/****************************************************************************/
/*!
@brief Configures the device's Adafruit IO credentials. This method
should be used only if filesystem-backed provisioning is
not available.
*/
/****************************************************************************/
void Wippersnapper::set_user_key() {
WS_DEBUG_PRINTLN("ERROR: Please define a network interface!");
}
// Decoders //
/****************************************************************************/
/*!
@brief Configures an analog input pin according to a
wippersnapper_pin_v1_ConfigurePinRequest message.
@param pinMsg
Pointer to a wippersnapper_pin_v1_ConfigurePinRequest message.
@returns True if analog pin configured successfully, False otherwise.
*/
/****************************************************************************/
bool Wippersnapper::configAnalogInPinReq(
wippersnapper_pin_v1_ConfigurePinRequest *pinMsg) {
bool is_success = true;
#if defined(ARDUINO_ARCH_RP2040)
char *pinName = pinMsg->pin_name + 1;
int pin = atoi(pinName);
#else
char *pinName = pinMsg->pin_name + 1;
int pin = atoi(pinName);
#endif
if (pinMsg->request_type ==
wippersnapper_pin_v1_ConfigurePinRequest_RequestType_REQUEST_TYPE_CREATE) {
WS._analogIO->initAnalogInputPin(pin, pinMsg->period, pinMsg->pull,
pinMsg->analog_read_mode);
} else if (
pinMsg->request_type ==
wippersnapper_pin_v1_ConfigurePinRequest_RequestType_REQUEST_TYPE_DELETE) {
WS._analogIO->deinitAnalogPin(pinMsg->direction, pin);
} else {
WS_DEBUG_PRINTLN("ERROR: Could not decode analog pin request!");
is_success = false;
}
return is_success;
}
/****************************************************************************/
/*!
@brief Configures a pin according to a
wippersnapper_pin_v1_ConfigurePinRequest message.
@param pinMsg
Pointer to a wippersnapper_pin_v1_ConfigurePinRequest message.
@returns True if pin configured successfully, False otherwise.
*/
/****************************************************************************/
bool Wippersnapper::configureDigitalPinReq(
wippersnapper_pin_v1_ConfigurePinRequest *pinMsg) {
bool is_success = true;
char *pinName = pinMsg->pin_name + 1;
int pin = atoi(pinName);
if (pinMsg->request_type ==
wippersnapper_pin_v1_ConfigurePinRequest_RequestType_REQUEST_TYPE_CREATE) {
// Initialize GPIO pin
WS._digitalGPIO->initDigitalPin(pinMsg->direction, pin, pinMsg->period,
pinMsg->pull);
} else if (
pinMsg->request_type ==
wippersnapper_pin_v1_ConfigurePinRequest_RequestType_REQUEST_TYPE_DELETE) {
// Delete digital GPIO pin
WS._digitalGPIO->deinitDigitalPin(pinMsg->direction, pin);
} else {
WS_DEBUG_PRINTLN("ERROR: Could not decode digital pin request type");
}
return is_success;
}
/*****************************************************************************/
/*!
@brief Decodes a repeated ConfigurePinRequests messages.
@param stream
Input stream to read from.
@param field
Message descriptor, usually autogenerated.
@param arg
Stores any information the decoding callback may need.
@returns True if pin configuration decoded successfully, False otherwise.
*/
/*****************************************************************************/
bool cbDecodePinConfigMsg(pb_istream_t *stream, const pb_field_t *field,
void **arg) {
(void)field; // marking unused parameters to avoid compiler warning
(void)arg; // marking unused parameters to avoid compiler warning
bool is_success = true;
WS_DEBUG_PRINTLN("cbDecodePinConfigMsg");
// pb_decode the stream into a pinReqMessage
wippersnapper_pin_v1_ConfigurePinRequest pinReqMsg =
wippersnapper_pin_v1_ConfigurePinRequest_init_zero;
if (!ws_pb_decode(stream, wippersnapper_pin_v1_ConfigurePinRequest_fields,
&pinReqMsg)) {
WS_DEBUG_PRINTLN("ERROR: Could not decode CreateSignalRequest")
is_success = false;
}
// Decode pin configuration request msg
if (pinReqMsg.mode == wippersnapper_pin_v1_Mode_MODE_DIGITAL) {
is_success = WS.configureDigitalPinReq(&pinReqMsg);
} else if (pinReqMsg.mode == wippersnapper_pin_v1_Mode_MODE_ANALOG) {
is_success = WS.configAnalogInPinReq(&pinReqMsg);
} else {
WS_DEBUG_PRINTLN("ERROR: Pin mode invalid!");
is_success = false;
}
return is_success;
}
/**************************************************************************/
/*!
@brief Decodes repeated PinEvents (digital pin write) messages.
@param stream
Input stream to read from.
@param field
Message descriptor, usually autogenerated.
@param arg
Stores any information the decoding callback may need.
@returns True if successfully decoded, False otherwise.
*/
/**************************************************************************/
bool cbDecodeDigitalPinWriteMsg(pb_istream_t *stream, const pb_field_t *field,
void **arg) {
bool is_success = true;
(void)field; // marking unused parameters to avoid compiler warning
(void)arg; // marking unused parameters to avoid compiler warning
WS_DEBUG_PRINTLN("cbDecodeDigitalPinWriteMsg");
// Decode stream into a PinEvent
wippersnapper_pin_v1_PinEvent pinEventMsg =
wippersnapper_pin_v1_PinEvent_init_zero;
if (!ws_pb_decode(stream, wippersnapper_pin_v1_PinEvent_fields,
&pinEventMsg)) {
WS_DEBUG_PRINTLN("ERROR: Could not decode PinEvents")
is_success = false;
}
// execute callback
char *pinName = pinEventMsg.pin_name + 1;
WS._digitalGPIO->digitalWriteSvc(atoi(pinName), atoi(pinEventMsg.pin_value));
return is_success;
}
/**************************************************************************/
/*!
@brief Sets payload callbacks inside the signal message's
submessage.
@param stream
Input stream to read from.
@param field
Message descriptor, usually autogenerated.
@param arg
Stores any information the decoding callback may need.
@returns True if successfully decoded, false otherwise.
*/
/**************************************************************************/
bool cbSignalMsg(pb_istream_t *stream, const pb_field_t *field, void **arg) {
(void)arg; // marking unused parameters to avoid compiler warning
bool is_success = true;
WS_DEBUG_PRINTLN("cbSignalMsg");
pb_size_t arr_sz = field->array_size;
WS_DEBUG_PRINT("Sub-messages found: ");
WS_DEBUG_PRINTLN(arr_sz);
if (field->tag ==
wippersnapper_signal_v1_CreateSignalRequest_pin_configs_tag) {
WS_DEBUG_PRINTLN("Signal Msg Tag: Pin Configuration");
// array to store the decoded CreateSignalRequests data
wippersnapper_pin_v1_ConfigurePinRequests msg =
wippersnapper_pin_v1_ConfigurePinRequests_init_zero;
// set up callback
msg.list.funcs.decode = cbDecodePinConfigMsg;
msg.list.arg = field->pData;
// decode each ConfigurePinRequest sub-message
if (!ws_pb_decode(stream, wippersnapper_pin_v1_ConfigurePinRequests_fields,
&msg)) {
WS_DEBUG_PRINTLN("ERROR: Could not decode CreateSignalRequest")
is_success = false;
WS.pinCfgCompleted = false;
}
// Is this the initial configuration?
if (!WS.pinCfgCompleted) {
WS_DEBUG_PRINTLN("Initial Pin Configuration Complete!");
WS.pinCfgCompleted = true;
}
} else if (field->tag ==
wippersnapper_signal_v1_CreateSignalRequest_pin_events_tag) {
WS_DEBUG_PRINTLN("Signal Msg Tag: Pin Event");
// array to store the decoded PinEvents data
wippersnapper_pin_v1_PinEvents msg =
wippersnapper_pin_v1_PinEvents_init_zero;
// set up callback
msg.list.funcs.decode = cbDecodeDigitalPinWriteMsg;
msg.list.arg = field->pData;
// decode each PinEvents sub-message
if (!ws_pb_decode(stream, wippersnapper_pin_v1_PinEvents_fields, &msg)) {
WS_DEBUG_PRINTLN("ERROR: Could not decode CreateSign2alRequest")
is_success = false;
}
} else {
WS_DEBUG_PRINTLN("ERROR: Unexpected signal msg tag.");
}
// once this is returned, pb_dec_submessage()
// decodes the submessage contents.
return is_success;
}
/**************************************************************************/
/*!
@brief Decodes a signal buffer protobuf message.
NOTE: Should be executed in-order after a new _buffer is received.
@param encodedSignalMsg
Encoded signal message.
@return true if successfully decoded signal message, false otherwise.
*/
/**************************************************************************/
bool Wippersnapper::decodeSignalMsg(
wippersnapper_signal_v1_CreateSignalRequest *encodedSignalMsg) {
bool is_success = true;
WS_DEBUG_PRINTLN("decodeSignalMsg");
/* Set up the payload callback, which will set up the callbacks for
each oneof payload field once the field tag is known */
encodedSignalMsg->cb_payload.funcs.decode = cbSignalMsg;
// decode the CreateSignalRequest, calls cbSignalMessage and assoc. callbacks
pb_istream_t stream = pb_istream_from_buffer(WS._buffer, WS.bufSize);
if (!ws_pb_decode(&stream, wippersnapper_signal_v1_CreateSignalRequest_fields,
encodedSignalMsg)) {
WS_DEBUG_PRINTLN(
"ERROR (decodeSignalMsg):, Could not decode CreateSignalRequest")
is_success = false;
}
return is_success;
}
/**************************************************************************/
/*!
@brief Called when signal topic receives a new message. Fills
shared buffer with data from payload.
@param data
Data from MQTT broker.
@param len
Length of data received from MQTT broker.
*/
/**************************************************************************/
void cbSignalTopic(char *data, uint16_t len) {
WS_DEBUG_PRINTLN("cbSignalTopic: New Msg on Signal Topic");
WS_DEBUG_PRINT(len);
WS_DEBUG_PRINTLN(" bytes.");
// zero-out current buffer
memset(WS._buffer, 0, sizeof(WS._buffer));
// copy data to buffer
memcpy(WS._buffer, data, len);
WS.bufSize = len;
// Empty struct for storing the signal message
WS._incomingSignalMsg = wippersnapper_signal_v1_CreateSignalRequest_init_zero;
// Attempt to decode a signal message
if (!WS.decodeSignalMsg(&WS._incomingSignalMsg)) {
WS_DEBUG_PRINTLN("ERROR: Failed to decode signal message");
}
}
/******************************************************************************************/
/*!
@brief Publishes an I2C response signal message to the broker.
@param msgi2cResponse
A pointer to an I2C response message typedef.
*/
/******************************************************************************************/
void publishI2CResponse(wippersnapper_signal_v1_I2CResponse *msgi2cResponse) {
size_t msgSz;
pb_get_encoded_size(&msgSz, wippersnapper_signal_v1_I2CResponse_fields,
msgi2cResponse);
WS_DEBUG_PRINTLN("Publishing Message: I2CResponse...");
if (!WS._mqtt->publish(WS._topic_signal_i2c_device, WS._buffer_outgoing,
msgSz, 0)) {
WS_DEBUG_PRINTLN("\tERROR: Failed to publish I2C Response!");
} else {
WS_DEBUG_PRINTLN("Published!");
}
}
/******************************************************************************************/
/*!
@brief Encodes an wippersnapper_signal_v1_I2CResponse message.
@param msgi2cResponse
A pointer to an wippersnapper_signal_v1_I2CResponse.
@return True if encoded successfully, False otherwise.
*/
/******************************************************************************************/
bool encodeI2CResponse(wippersnapper_signal_v1_I2CResponse *msgi2cResponse) {
memset(WS._buffer_outgoing, 0, sizeof(WS._buffer_outgoing));
pb_ostream_t ostream =
pb_ostream_from_buffer(WS._buffer_outgoing, sizeof(WS._buffer_outgoing));
if (!ws_pb_encode(&ostream, wippersnapper_signal_v1_I2CResponse_fields,
msgi2cResponse)) {
WS_DEBUG_PRINTLN("ERROR: Unable to encode I2C response message!");
return false;
}
return true;
}
/******************************************************************************************/
/*!
@brief Initializes an I2C bus component
@param msgInitRequest
A pointer to an i2c bus initialization message.
@return True if initialized successfully, False otherwise.
*/
/******************************************************************************************/
bool initializeI2CBus(wippersnapper_i2c_v1_I2CBusInitRequest msgInitRequest) {
// FUTURE TODO:we should add support for multiple i2c ports!
if (WS._isI2CPort0Init)
return true;
// Initialize bus
WS._i2cPort0 = new WipperSnapper_Component_I2C(&msgInitRequest);
WS.i2cComponents.push_back(WS._i2cPort0);
WS._isI2CPort0Init = WS._i2cPort0->isInitialized();
return WS._isI2CPort0Init;
}
/******************************************************************************************/
/*!
@brief Decodes a list of I2C Device Initialization messages.
@param stream
Incoming data stream from buffer.
@param field
Protobuf message's tag type.
@param arg
Optional arguments from pb_decode calling function.
@returns True if decoded successfully, False otherwise.
*/
/******************************************************************************************/
bool cbDecodeI2CDeviceInitRequestList(pb_istream_t *stream,
const pb_field_t *field, void **arg) {
(void)field; // marking unused parameters to avoid compiler warning
(void)arg; // marking unused parameters to avoid compiler warning
WS_DEBUG_PRINTLN("EXEC: cbDecodeI2CDeviceInitRequestList");
// Decode stream into individual msgI2CDeviceInitRequest messages
wippersnapper_i2c_v1_I2CDeviceInitRequest msgI2CDeviceInitRequest =
wippersnapper_i2c_v1_I2CDeviceInitRequest_init_zero;
if (!ws_pb_decode(stream, wippersnapper_i2c_v1_I2CDeviceInitRequest_fields,
&msgI2CDeviceInitRequest)) {
WS_DEBUG_PRINTLN("ERROR: Could not decode I2CDeviceInitRequest message.");
return false;
}
// Create response
wippersnapper_signal_v1_I2CResponse msgi2cResponse =
wippersnapper_signal_v1_I2CResponse_init_zero;
msgi2cResponse.which_payload =
wippersnapper_signal_v1_I2CResponse_resp_i2c_device_init_tag;
// Check I2C bus
if (!initializeI2CBus(msgI2CDeviceInitRequest.i2c_bus_init_req)) {
WS_DEBUG_PRINTLN("ERROR: Failed to initialize I2C Bus");
msgi2cResponse.payload.resp_i2c_device_init.bus_response =
WS._i2cPort0->getBusStatus();
if (!encodeI2CResponse(&msgi2cResponse)) {
WS_DEBUG_PRINTLN("ERROR: encoding I2C Response!");
return false;
}
publishI2CResponse(&msgi2cResponse);
return true;
}
WS._i2cPort0->initI2CDevice(&msgI2CDeviceInitRequest);
// Fill device's address and the initialization status
// TODO: The filling should be done within the method though?
msgi2cResponse.payload.resp_i2c_device_init.i2c_device_address =
msgI2CDeviceInitRequest.i2c_device_address;
msgi2cResponse.payload.resp_i2c_device_init.bus_response =
WS._i2cPort0->getBusStatus();
// Encode response
if (!encodeI2CResponse(&msgi2cResponse)) {
return false;
}
// Publish a response for the I2C device
publishI2CResponse(&msgi2cResponse);
return true;
}
/******************************************************************************************/
/*!
@brief Decodes an I2C signal request message and executes the
callback based on the message's tag. If successful,
publishes an I2C signal response back to the broker.
@param stream
Incoming data stream from buffer.
@param field
Protobuf message's tag type.
@param arg
Optional arguments from decoder calling function.
@returns True if decoded successfully, False otherwise.
*/
/******************************************************************************************/
bool cbDecodeSignalRequestI2C(pb_istream_t *stream, const pb_field_t *field,
void **arg) {
bool is_success = true;
(void)arg; // marking unused parameter to avoid compiler warning
WS_DEBUG_PRINTLN("cbDecodeSignalRequestI2C");
// Create I2C Response
wippersnapper_signal_v1_I2CResponse msgi2cResponse =
wippersnapper_signal_v1_I2CResponse_init_zero;
if (field->tag == wippersnapper_signal_v1_I2CRequest_req_i2c_scan_tag) {
WS_DEBUG_PRINTLN("I2C Scan Request");
// Decode I2CBusScanRequest
wippersnapper_i2c_v1_I2CBusScanRequest msgScanReq =
wippersnapper_i2c_v1_I2CBusScanRequest_init_zero;
if (!ws_pb_decode(stream, wippersnapper_i2c_v1_I2CBusScanRequest_fields,
&msgScanReq)) {
WS_DEBUG_PRINTLN(
"ERROR: Could not decode wippersnapper_i2c_v1_I2CBusScanRequest");
return false; // fail out if we can't decode the request
}
// Empty response message
wippersnapper_i2c_v1_I2CBusScanResponse scanResp =
wippersnapper_i2c_v1_I2CBusScanResponse_init_zero;
// Check I2C bus
if (!initializeI2CBus(msgScanReq.bus_init_request)) {
WS_DEBUG_PRINTLN("ERROR: Failed to initialize I2C Bus");
msgi2cResponse.payload.resp_i2c_scan.bus_response =
WS._i2cPort0->getBusStatus();
if (!encodeI2CResponse(&msgi2cResponse)) {
WS_DEBUG_PRINTLN("ERROR: encoding I2C Response!");
return false;
}
publishI2CResponse(&msgi2cResponse);
return true;
}
// Scan I2C bus
scanResp = WS._i2cPort0->scanAddresses();
// Fill I2CResponse
msgi2cResponse.which_payload =
wippersnapper_signal_v1_I2CResponse_resp_i2c_scan_tag;
memcpy(msgi2cResponse.payload.resp_i2c_scan.addresses_found,
scanResp.addresses_found, sizeof(scanResp.addresses_found));
msgi2cResponse.payload.resp_i2c_scan.addresses_found_count =
scanResp.addresses_found_count;
msgi2cResponse.payload.resp_i2c_scan.bus_response = scanResp.bus_response;
// Encode I2CResponse
if (!encodeI2CResponse(&msgi2cResponse)) {
return false;
}
} else if (
field->tag ==
wippersnapper_signal_v1_I2CRequest_req_i2c_device_init_requests_tag) {
WS_DEBUG_PRINTLN("I2C Device LIST Init Request Found!");
// Decode stream
wippersnapper_i2c_v1_I2CDeviceInitRequests msgI2CDeviceInitRequestList =
wippersnapper_i2c_v1_I2CDeviceInitRequests_init_zero;
// Set up callback
msgI2CDeviceInitRequestList.list.funcs.decode =
cbDecodeI2CDeviceInitRequestList;
msgI2CDeviceInitRequestList.list.arg = field->pData;
// Decode each sub-message
if (!ws_pb_decode(stream, wippersnapper_i2c_v1_I2CDeviceInitRequests_fields,
&msgI2CDeviceInitRequestList)) {
WS_DEBUG_PRINTLN("ERROR: Could not decode I2CDeviceInitRequests");
is_success = false;
}
// return so we don't publish an empty message, we already published within
// cbDecodeI2CDeviceInitRequestList() for each device
return is_success;
} else if (field->tag ==
wippersnapper_signal_v1_I2CRequest_req_i2c_device_init_tag) {
WS_DEBUG_PRINTLN("I2C Device Init Request Found!");
// Decode stream into an I2CDeviceInitRequest
wippersnapper_i2c_v1_I2CDeviceInitRequest msgI2CDeviceInitRequest =
wippersnapper_i2c_v1_I2CDeviceInitRequest_init_zero;
// Decode stream into struct, msgI2CDeviceInitRequest
if (!ws_pb_decode(stream, wippersnapper_i2c_v1_I2CDeviceInitRequest_fields,
&msgI2CDeviceInitRequest)) {
WS_DEBUG_PRINTLN("ERROR: Could not decode I2CDeviceInitRequest message.");
return false; // fail out if we can't decode
}
// Create empty response
msgi2cResponse = wippersnapper_signal_v1_I2CResponse_init_zero;
msgi2cResponse.which_payload =
wippersnapper_signal_v1_I2CResponse_resp_i2c_device_init_tag;
// Check I2C bus
if (!initializeI2CBus(msgI2CDeviceInitRequest.i2c_bus_init_req)) {
WS_DEBUG_PRINTLN("ERROR: Failed to initialize I2C Bus");
msgi2cResponse.payload.resp_i2c_device_init.bus_response =
WS._i2cPort0->getBusStatus();
if (!encodeI2CResponse(&msgi2cResponse)) {
WS_DEBUG_PRINTLN("ERROR: encoding I2C Response!");
return false;
}
publishI2CResponse(&msgi2cResponse);
return true;
}
// Initialize I2C device
WS._i2cPort0->initI2CDevice(&msgI2CDeviceInitRequest);
// Fill device's address and bus status
msgi2cResponse.payload.resp_i2c_device_init.i2c_device_address =
msgI2CDeviceInitRequest.i2c_device_address;
msgi2cResponse.payload.resp_i2c_device_init.bus_response =
WS._i2cPort0->getBusStatus();
// Encode response
if (!encodeI2CResponse(&msgi2cResponse)) {
return false;
}
} else if (field->tag ==
wippersnapper_signal_v1_I2CRequest_req_i2c_device_update_tag) {
WS_DEBUG_PRINTLN("=> INCOMING REQUEST: I2CDeviceUpdateRequest");
// New I2CDeviceUpdateRequest message
wippersnapper_i2c_v1_I2CDeviceUpdateRequest msgI2CDeviceUpdateRequest =
wippersnapper_i2c_v1_I2CDeviceUpdateRequest_init_zero;
// Decode stream into message
if (!ws_pb_decode(stream,
wippersnapper_i2c_v1_I2CDeviceUpdateRequest_fields,
&msgI2CDeviceUpdateRequest)) {
WS_DEBUG_PRINTLN(
"ERROR: Could not decode I2CDeviceUpdateRequest message.");
return false; // fail out if we can't decode
}
// Empty I2C response to fill out
msgi2cResponse = wippersnapper_signal_v1_I2CResponse_init_zero;
msgi2cResponse.which_payload =
wippersnapper_signal_v1_I2CResponse_resp_i2c_device_update_tag;
// Update I2C device's properties
WS._i2cPort0->updateI2CDeviceProperties(&msgI2CDeviceUpdateRequest);
// Fill address
msgi2cResponse.payload.resp_i2c_device_update.i2c_device_address =
msgI2CDeviceUpdateRequest.i2c_device_address;
msgi2cResponse.payload.resp_i2c_device_update.bus_response =
WS._i2cPort0->getBusStatus();
// Encode response
if (!encodeI2CResponse(&msgi2cResponse)) {
return false;
}
} else if (field->tag ==
wippersnapper_signal_v1_I2CRequest_req_i2c_device_deinit_tag) {
WS_DEBUG_PRINTLN("NEW COMMAND: I2C Device Deinit");
// Decode stream into an I2CDeviceDeinitRequest
wippersnapper_i2c_v1_I2CDeviceDeinitRequest msgI2CDeviceDeinitRequest =
wippersnapper_i2c_v1_I2CDeviceDeinitRequest_init_zero;
// Decode stream into struct, msgI2CDeviceDeinitRequest
if (!ws_pb_decode(stream,
wippersnapper_i2c_v1_I2CDeviceDeinitRequest_fields,
&msgI2CDeviceDeinitRequest)) {
WS_DEBUG_PRINTLN(
"ERROR: Could not decode I2CDeviceDeinitRequest message.");
return false; // fail out if we can't decode
}
// Empty I2C response to fill out
msgi2cResponse = wippersnapper_signal_v1_I2CResponse_init_zero;
msgi2cResponse.which_payload =
wippersnapper_signal_v1_I2CResponse_resp_i2c_device_deinit_tag;
// Deinitialize I2C device
WS._i2cPort0->deinitI2CDevice(&msgI2CDeviceDeinitRequest);
// Fill deinit response
msgi2cResponse.payload.resp_i2c_device_deinit.i2c_device_address =
msgI2CDeviceDeinitRequest.i2c_device_address;
msgi2cResponse.payload.resp_i2c_device_deinit.bus_response =
WS._i2cPort0->getBusStatus();
// Encode response
if (!encodeI2CResponse(&msgi2cResponse)) {
return false;
}
} else if (field->tag ==
wippersnapper_signal_v1_I2CRequest_req_i2c_device_out_write_tag) {
WS_DEBUG_PRINTLN("[app] I2C Device Output Write");
// Decode stream into an I2CDeviceDeinitRequest
wippersnapper_i2c_v1_I2CDeviceOutputWrite msgDeviceWrite =
wippersnapper_i2c_v1_I2CDeviceOutputWrite_init_zero;
// Decode stream into struct, msgI2CDeviceDeinitRequest
if (!ws_pb_decode(stream, wippersnapper_i2c_v1_I2CDeviceOutputWrite_fields,
&msgDeviceWrite)) {
WS_DEBUG_PRINTLN(
"[app] ERROR: Failed decoding I2CDeviceOutputWrite message.");
return false;
}
if (!WS._i2cPort0->Handle_I2cDeviceOutputWrite(&msgDeviceWrite)) {
WS_DEBUG_PRINTLN("[app] ERROR: Failed to write to I2C output device.");
return false; // fail out if we can't decode, we don't have a response to
// publish
}
WS_DEBUG_PRINTLN("[app] I2C Device Output Write Done");
return true; // we successfully wrote to the device, this subtype has no
// response to publish to IO
} else {
WS_DEBUG_PRINTLN("ERROR: Undefined I2C message tag");
return false; // fail out, we didn't encode anything to publish
}
// Publish the I2CResponse
publishI2CResponse(&msgi2cResponse);
return is_success;
}
/**************************************************************************/
/*!
@brief Called when i2c signal sub-topic receives a new message and
attempts to decode a signal request message.
@param data
Incoming data from MQTT broker.
@param len
Length of incoming data.
*/
/**************************************************************************/
void cbSignalI2CReq(char *data, uint16_t len) {
WS_DEBUG_PRINTLN("* NEW MESSAGE [Topic: Signal-I2C]: ");
WS_DEBUG_PRINT(len);
WS_DEBUG_PRINTLN(" bytes.");
// zero-out current buffer
memset(WS._buffer, 0, sizeof(WS._buffer));
// copy mqtt data into buffer
memcpy(WS._buffer, data, len);
WS.bufSize = len;
// Zero-out existing I2C signal msg.
WS.msgSignalI2C = wippersnapper_signal_v1_I2CRequest_init_zero;
// Set up the payload callback, which will set up the callbacks for
// each oneof payload field once the field tag is known
WS.msgSignalI2C.cb_payload.funcs.decode = cbDecodeSignalRequestI2C;
// Decode I2C signal request
pb_istream_t istream = pb_istream_from_buffer(WS._buffer, WS.bufSize);
if (!ws_pb_decode(&istream, wippersnapper_signal_v1_I2CRequest_fields,
&WS.msgSignalI2C))
WS_DEBUG_PRINTLN("ERROR: Unable to decode I2C message");
}
/******************************************************************************************/
/*!
@brief Decodes a servo message and dispatches to the servo component.
@param stream
Incoming data stream from buffer.
@param field
Protobuf message's tag type.
@param arg
Optional arguments from decoder calling function.
@returns True if decoded and executed successfully, False otherwise.
*/
/******************************************************************************************/
bool cbDecodeServoMsg(pb_istream_t *stream, const pb_field_t *field,
void **arg) {
WS_DEBUG_PRINTLN("Decoding Servo Message...");
(void)arg; // marking unused parameter to avoid compiler warning
if (field->tag == wippersnapper_signal_v1_ServoRequest_servo_attach_tag) {
WS_DEBUG_PRINTLN("GOT: Servo Attach");
// Attempt to decode contents of servo_attach message
wippersnapper_servo_v1_ServoAttachRequest msgServoAttachReq =
wippersnapper_servo_v1_ServoAttachRequest_init_zero;
if (!ws_pb_decode(stream, wippersnapper_servo_v1_ServoAttachRequest_fields,
&msgServoAttachReq)) {
WS_DEBUG_PRINTLN(
"ERROR: Could not decode wippersnapper_servo_v1_ServoAttachRequest");
return false; // fail out if we can't decode the request
}
// execute servo attach request
char *servoPin = msgServoAttachReq.servo_pin + 1;
bool attached = true;
if (!WS._servoComponent->servo_attach(
atoi(servoPin), msgServoAttachReq.min_pulse_width,
msgServoAttachReq.max_pulse_width, msgServoAttachReq.servo_freq)) {
WS_DEBUG_PRINTLN("ERROR: Unable to attach servo to pin!");
attached = false;
} else {
WS_DEBUG_PRINT("ATTACHED servo w/minPulseWidth: ");
WS_DEBUG_PRINT(msgServoAttachReq.min_pulse_width);
WS_DEBUG_PRINT(" uS and maxPulseWidth: ");
WS_DEBUG_PRINT(msgServoAttachReq.min_pulse_width);
WS_DEBUG_PRINT("uS on pin: ");
WS_DEBUG_PRINTLN(servoPin);
}
// Create and fill a servo response message
size_t msgSz; // message's encoded size
wippersnapper_signal_v1_ServoResponse msgServoResp =
wippersnapper_signal_v1_ServoResponse_init_zero;
msgServoResp.which_payload =
wippersnapper_signal_v1_ServoResponse_servo_attach_resp_tag;
msgServoResp.payload.servo_attach_resp.attach_success = attached;
strcpy(msgServoResp.payload.servo_attach_resp.servo_pin,
msgServoAttachReq.servo_pin);
// Encode and publish response back to broker
memset(WS._buffer_outgoing, 0, sizeof(WS._buffer_outgoing));
pb_ostream_t ostream = pb_ostream_from_buffer(WS._buffer_outgoing,
sizeof(WS._buffer_outgoing));
if (!ws_pb_encode(&ostream, wippersnapper_signal_v1_ServoResponse_fields,
&msgServoResp)) {
WS_DEBUG_PRINTLN("ERROR: Unable to encode servo response message!");
return false;
}
pb_get_encoded_size(&msgSz, wippersnapper_signal_v1_ServoResponse_fields,
&msgServoResp);
WS_DEBUG_PRINT("-> Servo Attach Response...");
WS._mqtt->publish(WS._topic_signal_servo_device, WS._buffer_outgoing, msgSz,
1);
WS_DEBUG_PRINTLN("Published!");
} else if (field->tag ==
wippersnapper_signal_v1_ServoRequest_servo_write_tag) {
WS_DEBUG_PRINTLN("GOT: Servo Write");
// Attempt to decode contents of servo write message
wippersnapper_servo_v1_ServoWriteRequest msgServoWriteReq =
wippersnapper_servo_v1_ServoWriteRequest_init_zero;
if (!ws_pb_decode(stream, wippersnapper_servo_v1_ServoWriteRequest_fields,
&msgServoWriteReq)) {
WS_DEBUG_PRINTLN(
"ERROR: Could not decode wippersnapper_servo_v1_ServoWriteRequest");
return false; // fail out if we can't decode the request
}
// execute servo write request
char *servoPin = msgServoWriteReq.servo_pin + 1;
WS_DEBUG_PRINT("Writing pulse width of ");
WS_DEBUG_PRINT((int)msgServoWriteReq.pulse_width);
WS_DEBUG_PRINT("uS to servo on pin#: ");
WS_DEBUG_PRINTLN(servoPin);
WS._servoComponent->servo_write(atoi(servoPin),
(int)msgServoWriteReq.pulse_width);
} else if (field->tag ==
wippersnapper_signal_v1_ServoRequest_servo_detach_tag) {
WS_DEBUG_PRINTLN("GOT: Servo Detach");