diff --git a/bin/config/pokey.cfg b/bin/config/pokey.cfg index d3e6699..8ebbbd5 100644 --- a/bin/config/pokey.cfg +++ b/bin/config/pokey.cfg @@ -322,335 +322,25 @@ configuration = pin = 22, name = "I_OH_ELEC", type = "DIGITAL_OUTPUT" - }, - - { - pin = 28, - name = "S_OH_LIGHT_RWY2", - type = "DIGITAL_INPUT", - invert = true - }, - { - pin = 29, - name = "S_OH_LIGHT_RWY1", - type = "DIGITAL_INPUT", - invert = true - }, - { - pin = 34, - name = "B_STARTER_SOLENOID_2", - type = "DIGITAL_OUTPUT" - }, - { - pin = 35, - name = "B_STARTER_SOLENOID_1", - type = "DIGITAL_OUTPUT" - }, - { - pin = 36, - name = "S_OH_FUEL_PUMP_CR", - type = "DIGITAL_INPUT", - invert = true - }, - { - pin = 37, - name = "S_OH_FUEL_PUMP_LA", - type = "DIGITAL_INPUT", - invert = true - }, - { - pin = 38, - name = "S_OH_FUEL_PUMP_CL", - type = "DIGITAL_INPUT", - invert = true - }, - { - pin = 39, - name = "S_OH_FUEL_PUMP_RF", - type = "DIGITAL_INPUT", - invert = true - }, - { - pin = 40, - name = "S_OH_FUEL_PUMP_RA", - type = "DIGITAL_INPUT", - invert = true - }, - { - pin = 41, - name = "S_OH_FUEL_PUMP_LF", - type = "DIGITAL_INPUT", - invert = true - }, - { - pin = 48, - name = "S_OH_BUS_TRANSFER", - type = "DIGITAL_INPUT", - invert = true } - ) }, { - # pokey_3 - serialNumber = "26767", - name = "pokey_3", - pins = ( - { - pin = 1, - name = "I_OH_TEMP_PROBE", - type = "DIGITAL_OUTPUT" - }, - { - pin = 2, - name = "I_OH_CAPT_PITOT", - type = "DIGITAL_OUTPUT" - }, - { - pin = 3, - name = "I_OH_ELEV_PITOT1", - type = "DIGITAL_OUTPUT" - }, - { - pin = 4, - name = "I_OH_COWL_AI_L", - type = "DIGITAL_OUTPUT" - }, - { - pin = 5, - name = "I_OH_COWL_VALVE_L", - type = "DIGITAL_OUTPUT" - }, - { - pin = 6, - name = "I_OH_COWL_AI_R", - type = "DIGITAL_OUTPUT" - }, - { - pin = 7, - name = "I_OH_WAI_VALVE_R", - type = "DIGITAL_OUTPUT" - }, - { - pin = 8, - name = "I_OH_WINDOW_HEAT_OVT_FL", - type = "DIGITAL_OUTPUT" - }, - { - pin = 9, - name = "I_OH_AUX_PITOT", - type = "DIGITAL_OUTPUT" - }, - { - pin = 10, - name = "I_OH_CO_PITOT", - type = "DIGITAL_OUTPUT" - }, - { - pin = 11, - name = "I_OH_ALPHA_VANE1", - type = "DIGITAL_OUTPUT" - }, - { - pin = 12, - name = "I_OH_ENG_HYD_PUMP_R", - type = "DIGITAL_OUTPUT" - }, - { - pin = 13, - name = "I_OH_ELEV_PITOT2", - type = "DIGITAL_OUTPUT" - }, - { - pin = 14, - name = "I_OH_ALPHA_VANE2", - type = "DIGITAL_OUTPUT" - }, - { - pin = 15, - name = "I_OH_WINDOW_HEAT_FR", - type = "DIGITAL_OUTPUT" - }, - { - pin = 16, - name = "I_OH_WINDOW_HEAT_SR", - type = "DIGITAL_OUTPUT" - }, - { - pin = 18, - name = "I_OH_WINDOW_HEAT_OVT_SL", - type = "DIGITAL_OUTPUT" - }, - { - pin = 19, - name = "I_OH_WINDOW_HEAT_FL", - type = "DIGITAL_OUTPUT" - }, - { - pin = 20, - name = "I_OH_WINDOW_HEAT_SL", - type = "DIGITAL_OUTPUT" - }, - { - pin = 21, - name = "I_OH_WINDOW_HEAT_OVT_FR", - type = "DIGITAL_OUTPUT" - }, - { - pin = 22, - name = "I_OH_ELEC_HYD_PUMP_OVHT_1", - type = "DIGITAL_OUTPUT" - }, - { - pin = 23, - name = "I_OH_WINDOW_HEAT_OVT_SR", - type = "DIGITAL_OUTPUT" - }, - { - pin = 24, - name = "I_OH_WAI_VALVE_L", - type = "DIGITAL_OUTPUT" - }, - { - pin = 25, - name = "I_OH_BLEED_TRIP_L", - type = "DIGITAL_OUTPUT" - }, - { - pin = 26, - name = "I_OH_BLEED_TRIP_R", - type = "DIGITAL_OUTPUT" - }, - { - pin = 27, - name = "I_OH_WINGBODY_OVT_R", - type = "DIGITAL_OUTPUT" - }, - { - pin = 28, - name = "I_OH_DOOR_AFT_SERVICE", - type = "DIGITAL_OUTPUT" - }, - { - pin = 29, - name = "I_OH_WINGBODY_OVT_L", - type = "DIGITAL_OUTPUT" - }, - { - pin = 30, - name = "I_OH_PRES_MANUAL", - type = "DIGITAL_OUTPUT" - }, - { - pin = 31, - name = "I_OH_ELEC_HYD_PUMP_1", - type = "DIGITAL_OUTPUT" - }, - { - pin = 32, - name = "I_OH_DOOR_FWD_SERVICE", - type = "DIGITAL_OUTPUT" - }, - { - pin = 33, - name = "I_OH_DOOR_LEFT_FWD_OVERWING", - type = "DIGITAL_OUTPUT" - }, - { - pin = 34, - name = "I_OH_DOOR_RIGHT_FWD_OVERWING", - type = "DIGITAL_OUTPUT" - }, - { - pin = 35, - name = "I_OH_DOOR_EQUIP", - type = "DIGITAL_OUTPUT" - }, - { - pin = 36, - name = "I_OH_DOOR_LEFT_AFT_OVERWING", - type = "DIGITAL_OUTPUT" - }, - { - pin = 37, - name = "I_OH_DOOR_FWD_ENTRY", - type = "DIGITAL_OUTPUT" - }, - { - pin = 38, - name = "I_OH_DOOR_AFT_ENTRY", - type = "DIGITAL_OUTPUT" - }, - { - pin = 39, - name = "I_OH_DOOR_RIGHT_AFT_OVERWING", - type = "DIGITAL_OUTPUT" - }, - { - pin = 40, - name = "I_OH_DOOR_AFT_CARGO", - type = "DIGITAL_OUTPUT" - }, - { - pin = 41, - name = "I_OH_PACK_L", - type = "DIGITAL_OUTPUT" - }, - { - pin = 42, - name = "I_OH_PRES_AUTO_FAIL", - type = "DIGITAL_OUTPUT" - }, - { - pin = 43, - name = "I_OH_ENG_HYD_PUMP_1", - type = "DIGITAL_OUTPUT" - }, - { - pin = 44, - name = "I_OH_PRES_OFFSCHED", - type = "DIGITAL_OUTPUT" - }, - { - pin = 45, - name = "I_OH_PACK_R", - type = "DIGITAL_OUTPUT" - }, - { - pin = 46, - name = "I_OH_ELEC_HYD_PUMP_2", - type = "DIGITAL_OUTPUT" - }, - { - pin = 47, - name = "I_OH_DOOR_FWD_CARGO", - type = "DIGITAL_OUTPUT" - }, - { - pin = 48, - name = "I_OH_PRES_ALTN", - type = "DIGITAL_OUTPUT" + serialNumber="26701", + name = "test PWM", + pins = (), + pwm= ( + { + channel = 5, + name = "G_OH_EGT", + decription = "APU Exhaust Gas Temp", + units = "degrees", + leftDutyCycle = 62000, + rightDutyCycle = 18000, + period = 500000 # hw cycles } ) - }, - { - serialNumber = "26766", - name = "PWM", - servo = ( - { - channel = 1, - pin = 17, - period = 20, - name = "G_OH_EGT", - description = "Exhaust gas temp", - units = "degrees", - min = 0, - max = 710, - default = 0 - } - ) , - pins = () - } + } ) diff --git a/bin/config/pokey_reinvent2017.cfg b/bin/config/pokey_reinvent2017.cfg index 436946b..4d6d7b2 100644 --- a/bin/config/pokey_reinvent2017.cfg +++ b/bin/config/pokey_reinvent2017.cfg @@ -14,6 +14,17 @@ configuration = name = "I_OH_PRES_MANUAL", type = "DIGITAL_OUTPUT" } + ), + pwm= ( + { + channel = 5, + name = "G_OH_OUTFLOW_VALVE", + decription = "Outflow valve position", + units = "degrees", + leftDutyCycle = 18000, + rightDutyCycle = 62000, + period = 750000 # hw cycles + } ) } ) \ No newline at end of file diff --git a/lib/pokey/PoKeysLibCore.c b/lib/pokey/PoKeysLibCore.c index 5916199..4a1a79d 100755 --- a/lib/pokey/PoKeysLibCore.c +++ b/lib/pokey/PoKeysLibCore.c @@ -1,6 +1,6 @@ /* -Copyright (C) 2013 Matevž Bošnak (matevz@poscope.com) +Copyright (C) 2013 Matev� Bo�nak (matevz@poscope.com) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -14,794 +14,753 @@ Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -#include -#include "PoKeysLib.h" #include "PoKeysLibCore.h" +#include "PoKeysLib.h" #include "PoKeysLibCoreSockets.h" -#include "string.h" #include "stdio.h" +#include "string.h" +#include + //#define PK_COM_DEBUG -int32_t PKI_CheckInterface(struct hid_device_info * devInfo) -{ - if (devInfo->interface_number == 1) - return 1; +int32_t PKI_CheckInterface(struct hid_device_info *devInfo) { + if (devInfo->interface_number == 1) + return 1; - return 0; + return 0; } // Connection specific commands -int32_t PK_EnumerateUSBDevices() -{ - int32_t numDevices = 0; - struct hid_device_info *devs, *cur_dev; - - devs = hid_enumerate(0x1DC3, 0x1001); - cur_dev = devs; - - while (cur_dev) - { - /*printf("Device Found\n"); - printf(" Serial: %ls\n", cur_dev->serial_number); - printf(" Product: %ls\n", cur_dev->product_string); - printf(" Interface: %d\n", cur_dev->interface_number); - printf("\n");*/ - - if (PKI_CheckInterface(cur_dev)) - { - numDevices++; - } - - cur_dev = cur_dev->next; - } - hid_free_enumeration(devs); - - devs = hid_enumerate(0x1DC3, 0x1002); - cur_dev = devs; - - while (cur_dev) - { - /*printf("Device Found\n"); - printf(" Serial: %ls\n", cur_dev->serial_number); - printf(" Product: %ls\n", cur_dev->product_string); - printf(" Interface: %d\n", cur_dev->interface_number); - printf("\n");*/ - if (cur_dev->interface_number == -1) numDevices++; - cur_dev = cur_dev->next; +int32_t PK_EnumerateUSBDevices() { + int32_t numDevices = 0; + struct hid_device_info *devs, *cur_dev; + + devs = hid_enumerate(0x1DC3, 0x1001); + cur_dev = devs; + + while (cur_dev) { + /*printf("Device Found\n"); + printf(" Serial: %ls\n", cur_dev->serial_number); + printf(" Product: %ls\n", cur_dev->product_string); + printf(" Interface: %d\n", cur_dev->interface_number); + printf("\n");*/ + + if (PKI_CheckInterface(cur_dev)) { + numDevices++; } - hid_free_enumeration(devs); + + cur_dev = cur_dev->next; + } + hid_free_enumeration(devs); + + devs = hid_enumerate(0x1DC3, 0x1002); + cur_dev = devs; + + while (cur_dev) { + /*printf("Device Found\n"); + printf(" Serial: %ls\n", cur_dev->serial_number); + printf(" Product: %ls\n", cur_dev->product_string); + printf(" Interface: %d\n", cur_dev->interface_number); + printf("\n");*/ + if (cur_dev->interface_number == -1) + numDevices++; + cur_dev = cur_dev->next; + } + hid_free_enumeration(devs); #ifdef POKEYSLIB_USE_LIBUSB - numDevices += PK_EnumerateFastUSBDevices(); + numDevices += PK_EnumerateFastUSBDevices(); #endif - return numDevices; + return numDevices; } -int32_t PK_GetCurrentDeviceConnectionType(sPoKeysDevice* device) -{ - return device->connectionType; +int32_t PK_GetCurrentDeviceConnectionType(sPoKeysDevice *device) { + return device->connectionType; } -void InitializeNewDevice(sPoKeysDevice* device) -{ - uint32_t i; - memset(&device->info, 0, sizeof(sPoKeysDevice_Info)); - memset(&device->DeviceData, 0, sizeof(sPoKeysDevice_Data)); - - device->netDeviceData = 0; - - memset(&device->matrixKB, 0, sizeof(sMatrixKeyboard)); - memset(&device->PWM, 0, sizeof(sPoKeysPWM)); - memset(&device->LCD, 0, sizeof(sPoKeysLCD)); - +void InitializeNewDevice(sPoKeysDevice *device) { + uint32_t i; + memset(&device->info, 0, sizeof(sPoKeysDevice_Info)); + memset(&device->DeviceData, 0, sizeof(sPoKeysDevice_Data)); - device->FastEncodersConfiguration = 0; - device->FastEncodersOptions = 0; - device->UltraFastEncoderConfiguration = 0; - device->UltraFastEncoderOptions = 0; + device->netDeviceData = 0; - device->UltraFastEncoderFilter = 0; + memset(&device->matrixKB, 0, sizeof(sMatrixKeyboard)); + memset(&device->PWM, 0, sizeof(sPoKeysPWM)); + memset(&device->LCD, 0, sizeof(sPoKeysLCD)); - memset(device->request, 0, 64); - memset(device->response, 0, 64); + device->FastEncodersConfiguration = 0; + device->FastEncodersOptions = 0; + device->UltraFastEncoderConfiguration = 0; + device->UltraFastEncoderOptions = 0; - device->sendRetries = 3; - device->readRetries = 10; - device->socketTimeout = 100; + device->UltraFastEncoderFilter = 0; - PK_DeviceDataGet(device); + memset(device->request, 0, 64); + memset(device->response, 0, 64); - device->Pins = (sPoKeysPinData*)malloc(sizeof(sPoKeysPinData) * device->info.iPinCount); - memset(device->Pins, 0, sizeof(sPoKeysPinData) * device->info.iPinCount); + device->sendRetries = 3; + device->readRetries = 10; + device->socketTimeout = 100; + PK_DeviceDataGet(device); - for (i = 0; i < device->info.iPinCount; i++) - { - if (PK_IsCounterAvailable(device, i)) - { - device->Pins[i].DigitalCounterAvailable = 1; - } else - { - device->Pins[i].DigitalCounterAvailable = 0; - } - } + device->Pins = + (sPoKeysPinData *)malloc(sizeof(sPoKeysPinData) * device->info.iPinCount); + memset(device->Pins, 0, sizeof(sPoKeysPinData) * device->info.iPinCount); - device->Encoders = (sPoKeysEncoder*)malloc(sizeof(sPoKeysEncoder) * device->info.iEncodersCount); - memset(device->Encoders, 0, sizeof(sPoKeysEncoder) * device->info.iEncodersCount); - - if (device->info.iEasySensors) - { - device->EasySensors = (sPoKeysEasySensor*)malloc(sizeof(sPoKeysEasySensor) * device->info.iEasySensors); - memset(device->EasySensors, 0, sizeof(sPoKeysEasySensor) * device->info.iEasySensors); - } else - { - device->EasySensors = NULL; + for (i = 0; i < device->info.iPinCount; i++) { + if (PK_IsCounterAvailable(device, i)) { + device->Pins[i].DigitalCounterAvailable = 1; + } else { + device->Pins[i].DigitalCounterAvailable = 0; } - - device->PWM.PWMduty = (uint32_t*)malloc(sizeof(uint32_t) * device->info.iPWMCount); - memset(device->PWM.PWMduty, 0, sizeof(uint32_t) * device->info.iPWMCount); - - device->PWM.PWMenabledChannels = (unsigned char*)malloc(sizeof(unsigned char) * device->info.iPWMCount); - memset(device->PWM.PWMenabledChannels, 0, sizeof(unsigned char) * device->info.iPWMCount); - device->PWM.PWMpinIDs = (unsigned char*)malloc(sizeof(unsigned char) * device->info.iPWMCount); - memset(device->PWM.PWMpinIDs, 0, sizeof(unsigned char) * device->info.iPWMCount); - - PK_FillPWMPinNumbers(device); - - device->PoExtBusData = (unsigned char*)malloc(sizeof(unsigned char) * device->info.iPoExtBus); - - device->MatrixLED = (sPoKeysMatrixLED*)malloc(sizeof(sPoKeysMatrixLED) * device->info.iMatrixLED); - memset(device->MatrixLED, 0, sizeof(sPoKeysMatrixLED) * device->info.iMatrixLED); - - memset(&device->PEv2, 0, sizeof(sPoKeysPEv2)); - - device-> multiPartBuffer = malloc(512); - if (device->multiPartBuffer <= 0) device->multiPartBuffer = 0; + } + + device->Encoders = (sPoKeysEncoder *)malloc(sizeof(sPoKeysEncoder) * + device->info.iEncodersCount); + memset(device->Encoders, 0, + sizeof(sPoKeysEncoder) * device->info.iEncodersCount); + + if (device->info.iEasySensors) { + device->EasySensors = (sPoKeysEasySensor *)malloc( + sizeof(sPoKeysEasySensor) * device->info.iEasySensors); + memset(device->EasySensors, 0, + sizeof(sPoKeysEasySensor) * device->info.iEasySensors); + } else { + device->EasySensors = NULL; + } + + device->PWM.PWMduty = + (uint32_t *)malloc(sizeof(uint32_t) * device->info.iPWMCount); + memset(device->PWM.PWMduty, 0, sizeof(uint32_t) * device->info.iPWMCount); + + device->PWM.PWMenabledChannels = + (unsigned char *)malloc(sizeof(unsigned char) * device->info.iPWMCount); + memset(device->PWM.PWMenabledChannels, 0, + sizeof(unsigned char) * device->info.iPWMCount); + device->PWM.PWMpinIDs = + (unsigned char *)malloc(sizeof(unsigned char) * device->info.iPWMCount); + memset(device->PWM.PWMpinIDs, 0, + sizeof(unsigned char) * device->info.iPWMCount); + + PK_FillPWMPinNumbers(device); + + device->PoExtBusData = + (unsigned char *)malloc(sizeof(unsigned char) * device->info.iPoExtBus); + + device->MatrixLED = (sPoKeysMatrixLED *)malloc(sizeof(sPoKeysMatrixLED) * + device->info.iMatrixLED); + memset(device->MatrixLED, 0, + sizeof(sPoKeysMatrixLED) * device->info.iMatrixLED); + + memset(&device->PEv2, 0, sizeof(sPoKeysPEv2)); + + device->multiPartBuffer = malloc(512); + if (device->multiPartBuffer <= 0) + device->multiPartBuffer = 0; #ifdef USE_ALIGN_TEST - device->alignTest1 = 1; - device->alignTest2 = 2; - device->alignTest3 = 3; - device->alignTest4 = 4; - device->alignTest5 = 5; - device->alignTest6 = 6; - device->alignTest7 = 7; - device->alignTest8 = 8; - device->alignTest9 = 9; - device->alignTest10 = 10; - device->alignTest11 = 11; + device->alignTest1 = 1; + device->alignTest2 = 2; + device->alignTest3 = 3; + device->alignTest4 = 4; + device->alignTest5 = 5; + device->alignTest6 = 6; + device->alignTest7 = 7; + device->alignTest8 = 8; + device->alignTest9 = 9; + device->alignTest10 = 10; + device->alignTest11 = 11; #endif } -void CleanDevice(sPoKeysDevice* device) -{ - free(device->Pins); - device->Pins = NULL; - free(device->Encoders); - device->Encoders = NULL; - free(device->PWM.PWMduty); - device->PWM.PWMduty = NULL; - free(device->PWM.PWMenabledChannels); - device->PWM.PWMenabledChannels = NULL; - free(device->PWM.PWMpinIDs); - device->PWM.PWMpinIDs = NULL; - free(device->PoExtBusData); - device->PoExtBusData = NULL; - free(device->MatrixLED); - device->MatrixLED = NULL; - - if (device->multiPartBuffer != NULL) - { - free(device->multiPartBuffer); - device->multiPartBuffer = NULL; - } - - if (device->EasySensors != NULL) - { - free(device->EasySensors); - device->EasySensors = NULL; - } - - if (device->netDeviceData != NULL) - { - free(device->netDeviceData); - device->netDeviceData = NULL; - } +void CleanDevice(sPoKeysDevice *device) { + free(device->Pins); + device->Pins = NULL; + free(device->Encoders); + device->Encoders = NULL; + free(device->PWM.PWMduty); + device->PWM.PWMduty = NULL; + free(device->PWM.PWMenabledChannels); + device->PWM.PWMenabledChannels = NULL; + free(device->PWM.PWMpinIDs); + device->PWM.PWMpinIDs = NULL; + free(device->PoExtBusData); + device->PoExtBusData = NULL; + free(device->MatrixLED); + device->MatrixLED = NULL; + + if (device->multiPartBuffer != NULL) { + free(device->multiPartBuffer); + device->multiPartBuffer = NULL; + } + + if (device->EasySensors != NULL) { + free(device->EasySensors); + device->EasySensors = NULL; + } + + if (device->netDeviceData != NULL) { + free(device->netDeviceData); + device->netDeviceData = NULL; + } } -void PK_ReleaseDeviceStructure(sPoKeysDevice* device) -{ - CleanDevice(device); +void PK_ReleaseDeviceStructure(sPoKeysDevice *device) { CleanDevice(device); } + +void PK_CloneDeviceStructure(sPoKeysDevice *original, + sPoKeysDevice *destination) { + // Reserve memory... + destination->Pins = (sPoKeysPinData *)malloc(sizeof(sPoKeysPinData) * + original->info.iPinCount); + destination->Encoders = (sPoKeysEncoder *)malloc( + sizeof(sPoKeysEncoder) * original->info.iEncodersCount); + destination->PWM.PWMduty = + (uint32_t *)malloc(sizeof(uint32_t) * original->info.iPWMCount); + destination->PWM.PWMenabledChannels = + (unsigned char *)malloc(sizeof(unsigned char) * original->info.iPWMCount); + destination->PWM.PWMpinIDs = + (unsigned char *)malloc(sizeof(unsigned char) * original->info.iPWMCount); + destination->MatrixLED = (sPoKeysMatrixLED *)malloc( + sizeof(sPoKeysMatrixLED) * original->info.iMatrixLED); + + if (original->info.iEasySensors) { + destination->EasySensors = (sPoKeysEasySensor *)malloc( + sizeof(sPoKeysEasySensor) * original->info.iEasySensors); + } else { + destination->EasySensors = 0; + } + + // Network device information structure... + if (original->netDeviceData != 0) { + destination->netDeviceData = + (sPoKeysNetworkDeviceInfo *)malloc(sizeof(sPoKeysNetworkDeviceInfo)); + memcpy(destination->netDeviceData, original->netDeviceData, + sizeof(sPoKeysNetworkDeviceInfo)); + } else { + destination->netDeviceData = 0; + } + destination->PoExtBusData = + (unsigned char *)malloc(sizeof(unsigned char) * original->info.iPoExtBus); + + // Copy data + destination->devHandle = original->devHandle; + destination->devHandle2 = original->devHandle2; + + destination->info = original->info; + destination->DeviceData = original->DeviceData; + + memcpy(&destination->Pins[0], &original->Pins[0], + original->info.iPinCount * sizeof(sPoKeysPinData)); + memcpy(&destination->Encoders[0], &original->Encoders[0], + original->info.iEncodersCount * sizeof(sPoKeysEncoder)); + + if (original->info.iEasySensors) { + memcpy(&destination->EasySensors[0], &original->EasySensors[0], + original->info.iEasySensors * sizeof(sPoKeysEasySensor)); + } + + destination->matrixKB = original->matrixKB; + + destination->PWM.PWMperiod = original->PWM.PWMperiod; + memcpy(destination->PWM.PWMduty, original->PWM.PWMduty, + sizeof(uint32_t) * original->info.iPWMCount); + memcpy(destination->PWM.PWMenabledChannels, original->PWM.PWMenabledChannels, + sizeof(unsigned char) * original->info.iPWMCount); + memcpy(destination->PWM.PWMpinIDs, original->PWM.PWMpinIDs, + sizeof(unsigned char) * original->info.iPWMCount); + + memcpy(destination->MatrixLED, original->MatrixLED, + sizeof(sPoKeysMatrixLED) * original->info.iMatrixLED); + + destination->LCD = original->LCD; + + destination->PoNETmodule = original->PoNETmodule; + destination->PoIL = original->PoIL; + destination->RTC = original->RTC; + + destination->FastEncodersConfiguration = original->FastEncodersConfiguration; + destination->FastEncodersOptions = original->FastEncodersOptions; + destination->UltraFastEncoderConfiguration = + original->UltraFastEncoderConfiguration; + destination->UltraFastEncoderOptions = original->UltraFastEncoderOptions; + destination->UltraFastEncoderFilter = original->UltraFastEncoderFilter; + + memcpy(destination->PoExtBusData, original->PoExtBusData, + sizeof(unsigned char) * original->info.iPoExtBus); + + destination->connectionType = original->connectionType; + destination->requestID = original->requestID; } -void PK_CloneDeviceStructure(sPoKeysDevice* original, sPoKeysDevice *destination) -{ - // Reserve memory... - destination->Pins = (sPoKeysPinData*)malloc(sizeof(sPoKeysPinData) * original->info.iPinCount); - destination->Encoders = (sPoKeysEncoder*)malloc(sizeof(sPoKeysEncoder) * original->info.iEncodersCount); - destination->PWM.PWMduty = (uint32_t*)malloc(sizeof(uint32_t) * original->info.iPWMCount); - destination->PWM.PWMenabledChannels = (unsigned char*)malloc(sizeof(unsigned char) * original->info.iPWMCount); - destination->PWM.PWMpinIDs = (unsigned char*)malloc(sizeof(unsigned char) * original->info.iPWMCount); - destination->MatrixLED = (sPoKeysMatrixLED*)malloc(sizeof(sPoKeysMatrixLED) * original->info.iMatrixLED); - - if (original->info.iEasySensors) - { - destination->EasySensors = (sPoKeysEasySensor*)malloc(sizeof(sPoKeysEasySensor) * original->info.iEasySensors); - } else - { - destination->EasySensors = 0; - } - - // Network device information structure... - if (original->netDeviceData != 0) - { - destination->netDeviceData = (sPoKeysNetworkDeviceInfo *)malloc(sizeof(sPoKeysNetworkDeviceInfo)); - memcpy(destination->netDeviceData, original->netDeviceData, sizeof(sPoKeysNetworkDeviceInfo)); - } else - { - destination->netDeviceData = 0; - } - destination->PoExtBusData = (unsigned char*)malloc(sizeof(unsigned char) * original->info.iPoExtBus); - - - // Copy data - destination->devHandle = original->devHandle; - destination->devHandle2 = original->devHandle2; - - destination->info = original->info; - destination->DeviceData = original->DeviceData; - - memcpy(&destination->Pins[0], &original->Pins[0], - original->info.iPinCount * sizeof(sPoKeysPinData)); - memcpy(&destination->Encoders[0], &original->Encoders[0], - original->info.iEncodersCount * sizeof(sPoKeysEncoder)); - - - if (original->info.iEasySensors) - { - memcpy(&destination->EasySensors[0], &original->EasySensors[0], - original->info.iEasySensors * sizeof(sPoKeysEasySensor)); - } - - destination->matrixKB = original->matrixKB; - - destination->PWM.PWMperiod = original->PWM.PWMperiod; - memcpy(destination->PWM.PWMduty, original->PWM.PWMduty, - sizeof(uint32_t) * original->info.iPWMCount); - memcpy(destination->PWM.PWMenabledChannels, original->PWM.PWMenabledChannels, - sizeof(unsigned char) * original->info.iPWMCount); - memcpy(destination->PWM.PWMpinIDs, original->PWM.PWMpinIDs, - sizeof(unsigned char) * original->info.iPWMCount); +void *PK_FastUSBConnectToDevice(uint32_t deviceIndex); - memcpy(destination->MatrixLED, original->MatrixLED, - sizeof(sPoKeysMatrixLED) * original->info.iMatrixLED); +sPoKeysDevice *PK_ConnectToDevice(uint32_t deviceIndex) { + int32_t numDevices = 0; + struct hid_device_info *devs, *cur_dev; + sPoKeysDevice *tmpDevice; + void *devData; - destination->LCD = original->LCD; + devs = hid_enumerate(0x1DC3, 0x1001); + cur_dev = devs; - destination->PoNETmodule = original->PoNETmodule; - destination->PoIL = original->PoIL; - destination->RTC = original->RTC; + while (cur_dev) { + if (cur_dev->interface_number == 1) { + if (numDevices == deviceIndex) { + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); - destination->FastEncodersConfiguration = original->FastEncodersConfiguration; - destination->FastEncodersOptions = original->FastEncodersOptions; - destination->UltraFastEncoderConfiguration =original->UltraFastEncoderConfiguration; - destination->UltraFastEncoderOptions = original->UltraFastEncoderOptions; - destination->UltraFastEncoderFilter = original->UltraFastEncoderFilter; + // printf("Connect to this device..."); + tmpDevice->devHandle = (void *)hid_open_path(cur_dev->path); + tmpDevice->devHandle2 = NULL; - memcpy(destination->PoExtBusData, original->PoExtBusData, sizeof(unsigned char) * original->info.iPoExtBus); + tmpDevice->connectionType = PK_DeviceType_USBDevice; - destination->connectionType = original->connectionType; - destination->requestID = original->requestID; - -} - -void * PK_FastUSBConnectToDevice(uint32_t deviceIndex); - -sPoKeysDevice* PK_ConnectToDevice(uint32_t deviceIndex) -{ - int32_t numDevices = 0; - struct hid_device_info *devs, *cur_dev; - sPoKeysDevice* tmpDevice; - void * devData; - - devs = hid_enumerate(0x1DC3, 0x1001); - cur_dev = devs; - - while (cur_dev) - { - if (cur_dev->interface_number == 1) - { - if (numDevices == deviceIndex) - { - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - - //printf("Connect to this device..."); - tmpDevice->devHandle = (void*)hid_open_path(cur_dev->path); - tmpDevice->devHandle2 = NULL; - - tmpDevice->connectionType = PK_DeviceType_USBDevice; - - - if (tmpDevice->devHandle != NULL) - { - InitializeNewDevice(tmpDevice); - } else - { - free(tmpDevice); - tmpDevice = NULL; - } - //hid_set_nonblocking(devHandle); - hid_free_enumeration(devs); - return tmpDevice; - } - numDevices++; + if (tmpDevice->devHandle != NULL) { + InitializeNewDevice(tmpDevice); + } else { + free(tmpDevice); + tmpDevice = NULL; } - cur_dev = cur_dev->next; + // hid_set_nonblocking(devHandle); + hid_free_enumeration(devs); + return tmpDevice; + } + numDevices++; } - hid_free_enumeration(devs); - - // Continue with 0x1002 devices - devs = hid_enumerate(0x1DC3, 0x1002); - cur_dev = devs; - - while (cur_dev) - { - if (cur_dev->interface_number == -1) - { - if (numDevices == deviceIndex) - { - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - - //printf("Connect to this device..."); - tmpDevice->devHandle = (void*)hid_open_path(cur_dev->path); - tmpDevice->devHandle2 = NULL; - - tmpDevice->connectionType = PK_DeviceType_USBDevice; - - if (tmpDevice->devHandle != NULL) - { - InitializeNewDevice(tmpDevice); - } else - { - free(tmpDevice); - tmpDevice = NULL; - } - //hid_set_nonblocking(devHandle); - hid_free_enumeration(devs); - return tmpDevice; - } - numDevices++; + cur_dev = cur_dev->next; + } + hid_free_enumeration(devs); + + // Continue with 0x1002 devices + devs = hid_enumerate(0x1DC3, 0x1002); + cur_dev = devs; + + while (cur_dev) { + if (cur_dev->interface_number == -1) { + if (numDevices == deviceIndex) { + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); + + // printf("Connect to this device..."); + tmpDevice->devHandle = (void *)hid_open_path(cur_dev->path); + tmpDevice->devHandle2 = NULL; + + tmpDevice->connectionType = PK_DeviceType_USBDevice; + + if (tmpDevice->devHandle != NULL) { + InitializeNewDevice(tmpDevice); + } else { + free(tmpDevice); + tmpDevice = NULL; } - cur_dev = cur_dev->next; + // hid_set_nonblocking(devHandle); + hid_free_enumeration(devs); + return tmpDevice; + } + numDevices++; } - hid_free_enumeration(devs); + cur_dev = cur_dev->next; + } + hid_free_enumeration(devs); #ifdef POKEYSLIB_USE_LIBUSB - // Try connecting to the bulk interface of the PoKeys device... - devData = PK_FastUSBConnectToDevice(deviceIndex - numDevices); + // Try connecting to the bulk interface of the PoKeys device... + devData = PK_FastUSBConnectToDevice(deviceIndex - numDevices); - //void * devData = ConnectToFastUSBInterface(serialNumber); - if (devData != NULL) - { - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); + // void * devData = ConnectToFastUSBInterface(serialNumber); + if (devData != NULL) { + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); - tmpDevice->devHandle = NULL; - tmpDevice->devHandle2 = devData; + tmpDevice->devHandle = NULL; + tmpDevice->devHandle2 = devData; - tmpDevice->connectionType = PK_DeviceType_FastUSBDevice; - InitializeNewDevice(tmpDevice); - return tmpDevice; - } + tmpDevice->connectionType = PK_DeviceType_FastUSBDevice; + InitializeNewDevice(tmpDevice); + return tmpDevice; + } #endif - return NULL; + return NULL; } // Flags: // bits 7-1: deviceType specifier (2 - PoKeys56, 3 - PoKeys58, 4 - PoKeys16) // bit 0: use UDP -sPoKeysDevice* PK_ConnectToPoKeysDevice(uint32_t serialNumber, uint32_t checkForNetworkDevicesAndTimeout, uint32_t flags) -{ - int32_t numDevices = 0; - struct hid_device_info *devs, *cur_dev; - int32_t k; - sPoKeysDevice* tmpDevice; - uint8_t serialSearch[8]; - //uint8_t serialSearch58[8]; - - sPoKeysNetworkDeviceSummary * devices; - int32_t iNet; - - int devRange = 0; - uint8_t deviceTypeRequested = (flags >> 1) & 0x7F; - - +sPoKeysDevice * +PK_ConnectToPoKeysDevice(uint32_t serialNumber, + uint32_t checkForNetworkDevicesAndTimeout, + uint32_t flags) { + int32_t numDevices = 0; + struct hid_device_info *devs, *cur_dev; + int32_t k; + sPoKeysDevice *tmpDevice; + uint8_t serialSearch[8]; + // uint8_t serialSearch58[8]; + + sPoKeysNetworkDeviceSummary *devices; + int32_t iNet; + + int devRange = 0; + uint8_t deviceTypeRequested = (flags >> 1) & 0x7F; #ifdef POKEYSLIB_USE_LIBUSB - // Try connecting to fast USB interface first - void * devData = ConnectToFastUSBInterface(serialNumber); - if (devData != NULL) - { - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - - tmpDevice->devHandle = NULL; - tmpDevice->devHandle2 = devData; - - tmpDevice->connectionType = PK_DeviceType_FastUSBDevice; - InitializeNewDevice(tmpDevice); - return tmpDevice; - } + // Try connecting to fast USB interface first + void *devData = ConnectToFastUSBInterface(serialNumber); + if (devData != NULL) { + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); + + tmpDevice->devHandle = NULL; + tmpDevice->devHandle2 = devData; + + tmpDevice->connectionType = PK_DeviceType_FastUSBDevice; + InitializeNewDevice(tmpDevice); + return tmpDevice; + } #endif - devs = hid_enumerate(0x1DC3, 0x1001); - cur_dev = devs; + devs = hid_enumerate(0x1DC3, 0x1001); + cur_dev = devs; - sprintf((char*)serialSearch, "x.%05u", serialNumber % 100000); - //sprintf(serialSearch58, "3.%05u", serialNumber % 100000); + sprintf((char *)serialSearch, "x.%05u", serialNumber % 100000); + // sprintf(serialSearch58, "3.%05u", serialNumber % 100000); - while (cur_dev) - { - if ((cur_dev->interface_number == 1 && devRange == 0) || - (cur_dev->interface_number == 0 && devRange == 1)) - { - if (cur_dev->serial_number != 0 && cur_dev->serial_number[0] != 'P') - { - // Check the serial number first - for (k = 1; k < 8 && cur_dev->serial_number[k] != 0; k++) - { - if (cur_dev->serial_number[k] != serialSearch[k]) break; - } - - if (deviceTypeRequested == 2 && cur_dev->serial_number[0] != '2') k = 0; - if (deviceTypeRequested == 3 && cur_dev->serial_number[0] != '3') k = 0; - if (deviceTypeRequested == 4 && cur_dev->serial_number[0] != '4') k = 0; - - /* - for (k = 0; k < 8 && cur_dev->serial_number[k] != 0; k++) - { - if (cur_dev->serial_number[k] != serialSearch[k]) break; - } - - if (k != 7) - { - for (k = 0; k < 8 && cur_dev->serial_number[k] != 0; k++) - { - if (cur_dev->serial_number[k] != serialSearch58[k]) break; - } - }*/ - - if (k == 7) - { - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - - //printf("Connect to this device..."); - tmpDevice->devHandle = (void*)hid_open_path(cur_dev->path); - tmpDevice->devHandle2 = 0; - - tmpDevice->connectionType = PK_DeviceType_USBDevice; - if (tmpDevice->devHandle != NULL) - { - InitializeNewDevice(tmpDevice); - } else - { - free(tmpDevice); - tmpDevice = NULL; - } - //hid_set_nonblocking(devHandle); - hid_free_enumeration(devs); - return tmpDevice; - } - } else - { - // Old, PoKeys55 device - we must to connect and read the serial number... - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - tmpDevice->devHandle = (void*)hid_open_path(cur_dev->path); - tmpDevice->devHandle2 = 0; - - if (tmpDevice->devHandle != NULL) - { - InitializeNewDevice(tmpDevice); - } else - { - free(tmpDevice); - tmpDevice = NULL; - hid_free_enumeration(devs); - return NULL; - } - - tmpDevice->connectionType = PK_DeviceType_USBDevice; - if (tmpDevice->DeviceData.SerialNumber == serialNumber) - { - hid_free_enumeration(devs); - return tmpDevice; - } else - { - CleanDevice(tmpDevice); - free(tmpDevice); - } - } + while (cur_dev) { + if ((cur_dev->interface_number == 1 && devRange == 0) || + (cur_dev->interface_number == 0 && devRange == 1)) { + if (cur_dev->serial_number != 0 && cur_dev->serial_number[0] != 'P') { + // Check the serial number first + for (k = 1; k < 8 && cur_dev->serial_number[k] != 0; k++) { + if (cur_dev->serial_number[k] != serialSearch[k]) + break; + } - numDevices++; + if (deviceTypeRequested == 2 && cur_dev->serial_number[0] != '2') + k = 0; + if (deviceTypeRequested == 3 && cur_dev->serial_number[0] != '3') + k = 0; + if (deviceTypeRequested == 4 && cur_dev->serial_number[0] != '4') + k = 0; + + /* + for (k = 0; k < 8 && cur_dev->serial_number[k] != 0; k++) + { + if (cur_dev->serial_number[k] != serialSearch[k]) break; } - cur_dev = cur_dev->next; - if (cur_dev == NULL) + if (k != 7) { - devRange++; - switch (devRange) + for (k = 0; k < 8 && cur_dev->serial_number[k] != 0; k++) { - case 1: - hid_free_enumeration(devs); - devs = hid_enumerate(0x1DC3, 0x1001); - cur_dev = devs; - break; + if (cur_dev->serial_number[k] != serialSearch58[k]) break; } + }*/ + + if (k == 7) { + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); + + // printf("Connect to this device..."); + tmpDevice->devHandle = (void *)hid_open_path(cur_dev->path); + tmpDevice->devHandle2 = 0; + + tmpDevice->connectionType = PK_DeviceType_USBDevice; + if (tmpDevice->devHandle != NULL) { + InitializeNewDevice(tmpDevice); + } else { + free(tmpDevice); + tmpDevice = NULL; + } + // hid_set_nonblocking(devHandle); + hid_free_enumeration(devs); + return tmpDevice; + } + } else { + // Old, PoKeys55 device - we must to connect and read the serial + // number... + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); + tmpDevice->devHandle = (void *)hid_open_path(cur_dev->path); + tmpDevice->devHandle2 = 0; + + if (tmpDevice->devHandle != NULL) { + InitializeNewDevice(tmpDevice); + } else { + free(tmpDevice); + tmpDevice = NULL; + hid_free_enumeration(devs); + return NULL; } - } - hid_free_enumeration(devs); - - if (checkForNetworkDevicesAndTimeout) - { - devices = (sPoKeysNetworkDeviceSummary*)malloc(sizeof(sPoKeysNetworkDeviceSummary) * 16); - iNet = PK_SearchNetworkDevices(devices, checkForNetworkDevicesAndTimeout, serialNumber); - if (iNet > 16) iNet = 16; + tmpDevice->connectionType = PK_DeviceType_USBDevice; + if (tmpDevice->DeviceData.SerialNumber == serialNumber) { + hid_free_enumeration(devs); + return tmpDevice; + } else { + CleanDevice(tmpDevice); + free(tmpDevice); + } + } - for (k = 0; k < iNet; k++) - { - //printf("\nNetwork device found, serial = %lu at %u.%u.%u.%u", devices[k].SerialNumber, devices[k].IPaddress[0], devices[k].IPaddress[1], devices[k].IPaddress[2], devices[k].IPaddress[3]); - if (devices[k].SerialNumber == serialNumber) - { - if (flags & 1) devices[k].useUDP = 1; - tmpDevice = PK_ConnectToNetworkDevice(&devices[k]); - if (tmpDevice == NULL) - { - //CleanDevice(tmpDevice); - free(tmpDevice); - //printf("\nProblem connecting to the device..."); - } else - { - free(devices); - InitializeNewDevice(tmpDevice); - return tmpDevice; - } - } + numDevices++; + } + cur_dev = cur_dev->next; + + if (cur_dev == NULL) { + devRange++; + switch (devRange) { + case 1: + hid_free_enumeration(devs); + devs = hid_enumerate(0x1DC3, 0x1001); + cur_dev = devs; + break; + } + } + } + hid_free_enumeration(devs); + + if (checkForNetworkDevicesAndTimeout) { + devices = (sPoKeysNetworkDeviceSummary *)malloc( + sizeof(sPoKeysNetworkDeviceSummary) * 16); + iNet = PK_SearchNetworkDevices(devices, checkForNetworkDevicesAndTimeout, + serialNumber); + + if (iNet > 16) + iNet = 16; + + for (k = 0; k < iNet; k++) { + // printf("\nNetwork device found, serial = %lu at %u.%u.%u.%u", + // devices[k].SerialNumber, devices[k].IPaddress[0], + // devices[k].IPaddress[1], devices[k].IPaddress[2], + // devices[k].IPaddress[3]); + if (devices[k].SerialNumber == serialNumber) { + if (flags & 1) + devices[k].useUDP = 1; + tmpDevice = PK_ConnectToNetworkDevice(&devices[k]); + if (tmpDevice == NULL) { + // CleanDevice(tmpDevice); + free(tmpDevice); + // printf("\nProblem connecting to the device..."); + } else { + free(devices); + InitializeNewDevice(tmpDevice); + return tmpDevice; } - free(devices); + } } + free(devices); + } - return NULL; + return NULL; } - -sPoKeysDevice* PK_ConnectToDeviceWSerial(uint32_t serialNumber, uint32_t checkForNetworkDevicesAndTimeout) -{ - return PK_ConnectToPoKeysDevice(serialNumber, checkForNetworkDevicesAndTimeout, 0); +sPoKeysDevice * +PK_ConnectToDeviceWSerial(uint32_t serialNumber, + uint32_t checkForNetworkDevicesAndTimeout) { + return PK_ConnectToPoKeysDevice(serialNumber, + checkForNetworkDevicesAndTimeout, 0); } -sPoKeysDevice* PK_ConnectToDeviceWSerial_UDP(uint32_t serialNumber, uint32_t checkForNetworkDevicesAndTimeout) -{ - return PK_ConnectToPoKeysDevice(serialNumber, checkForNetworkDevicesAndTimeout, 1); +sPoKeysDevice * +PK_ConnectToDeviceWSerial_UDP(uint32_t serialNumber, + uint32_t checkForNetworkDevicesAndTimeout) { + return PK_ConnectToPoKeysDevice(serialNumber, + checkForNetworkDevicesAndTimeout, 1); } -void PK_DisconnectDevice(sPoKeysDevice* device) -{ - if (device != NULL) - { - if (device->connectionType == PK_DeviceType_NetworkDevice) - { - PK_DisconnectNetworkDevice(device); - } else - { +void PK_DisconnectDevice(sPoKeysDevice *device) { + if (device != NULL) { + if (device->connectionType == PK_DeviceType_NetworkDevice) { + PK_DisconnectNetworkDevice(device); + } else { #ifdef POKEYSLIB_USE_LIBUSB - // Disconnect the fast USB interface... - DisconnectFromFastUSBInterface(device->devHandle2); - device->devHandle2 = NULL; + // Disconnect the fast USB interface... + DisconnectFromFastUSBInterface(device->devHandle2); + device->devHandle2 = NULL; #endif - if ((hid_device*)device->devHandle != NULL) - { - hid_close((hid_device*)device->devHandle); - } - } - - CleanDevice(device); - free(device); + if ((hid_device *)device->devHandle != NULL) { + hid_close((hid_device *)device->devHandle); + } } + + CleanDevice(device); + free(device); + } } -int32_t CreateRequest(unsigned char * request, unsigned char type, unsigned char param1, unsigned char param2, unsigned char param3, unsigned char param4) -{ - if (request == NULL) return PK_ERR_NOT_CONNECTED; +int32_t CreateRequest(unsigned char *request, unsigned char type, + unsigned char param1, unsigned char param2, + unsigned char param3, unsigned char param4) { + if (request == NULL) + return PK_ERR_NOT_CONNECTED; - memset(request, 0, 64); + memset(request, 0, 64); - request[1] = type; - request[2] = param1; - request[3] = param2; - request[4] = param3; - request[5] = param4; + request[1] = type; + request[2] = param1; + request[3] = param2; + request[4] = param3; + request[5] = param4; - return PK_OK; + return PK_OK; } -int32_t PK_CustomRequest(sPoKeysDevice* device, unsigned char type, unsigned char param1, unsigned char param2, unsigned char param3, unsigned char param4) -{ - device->request[1] = type; - device->request[2] = param1; - device->request[3] = param2; - device->request[4] = param3; - device->request[5] = param4; +int32_t PK_CustomRequest(sPoKeysDevice *device, unsigned char type, + unsigned char param1, unsigned char param2, + unsigned char param3, unsigned char param4) { + device->request[1] = type; + device->request[2] = param1; + device->request[3] = param2; + device->request[4] = param3; + device->request[5] = param4; - return SendRequest(device); + return SendRequest(device); } -uint8_t getChecksum(uint8_t * data) -{ - uint8_t temp = 0; - uint32_t i; +uint8_t getChecksum(uint8_t *data) { + uint8_t temp = 0; + uint32_t i; - for (i = 0; i < 7; i++) - { - temp += data[i]; - } - return temp; + for (i = 0; i < 7; i++) { + temp += data[i]; + } + return temp; } int32_t LastRetryCount = 0; int32_t LastWaitCount = 0; - //#define PK_COM_DEBUG -int32_t SendRequest_multiPart(sPoKeysDevice* device) -{ - if (device == NULL) return PK_ERR_GENERIC; - if (device->connectionType == PK_DeviceType_NetworkDevice) - { - return SendEthRequestBig(device); - //return SendEthRequest(device); - //return PK_ERR_TRANSFER; - } +int32_t SendRequest_multiPart(sPoKeysDevice *device) { + if (device == NULL) + return PK_ERR_GENERIC; + if (device->connectionType == PK_DeviceType_NetworkDevice) { + return SendEthRequestBig(device); + // return SendEthRequest(device); + // return PK_ERR_TRANSFER; + } #ifdef POKEYSLIB_USE_LIBUSB - if (device->connectionType == PK_DeviceType_FastUSBDevice) - return SendRequestFastUSB_multiPart(device); - else - return PK_ERR_TRANSFER; -#else + if (device->connectionType == PK_DeviceType_FastUSBDevice) + return SendRequestFastUSB_multiPart(device); + else return PK_ERR_TRANSFER; +#else + return PK_ERR_TRANSFER; #endif } - //#define PK_COM_DEBUG -int32_t SendRequest(sPoKeysDevice* device) -{ - // Initialize variables - uint32_t waits = 0; - uint32_t retries = 0; - int32_t result = 0; - uint8_t bufferOut[65] = {0}; - - #ifdef PK_COM_DEBUG - int i; - #endif - - hid_device * devHandle; - - - - if (device == NULL) return PK_ERR_GENERIC; - if (device->connectionType == PK_DeviceType_NetworkDevice) - { - return SendEthRequest(device); - } +int32_t SendRequest(sPoKeysDevice *device) { + // Initialize variables + uint32_t waits = 0; + uint32_t retries = 0; + int32_t result = 0; + uint8_t bufferOut[65] = {0}; + + // #ifdef PK_COM_DEBUG + int i; + // #endif + + hid_device *devHandle; + + if (device == NULL) + return PK_ERR_GENERIC; + if (device->connectionType == PK_DeviceType_NetworkDevice) { + return SendEthRequest(device); + } #ifdef POKEYSLIB_USE_LIBUSB - if (device->connectionType == PK_DeviceType_FastUSBDevice) - return SendRequestFastUSB(device); + if (device->connectionType == PK_DeviceType_FastUSBDevice) + return SendRequestFastUSB(device); #endif - devHandle = (hid_device*)device->devHandle; + devHandle = (hid_device *)device->devHandle; + if (devHandle == NULL) + return PK_ERR_GENERIC; - if (devHandle == NULL) return PK_ERR_GENERIC; + // Request sending loop + while (retries++ < 2) { + device->request[0] = 0xBB; + device->request[6] = ++device->requestID; + device->request[7] = getChecksum(device->request); - // Request sending loop - while (retries++ < 2) - { - device->request[0] = 0xBB; - device->request[6] = ++device->requestID; - device->request[7] = getChecksum(device->request); - - memcpy(bufferOut + 1, device->request, 64); - - #ifdef PK_COM_DEBUG - printf("\n * SEND "); - for (i = 0; i < 10; i++) - { - printf("%X ", bufferOut[i]); - } - #endif - - result = hid_write(devHandle, bufferOut, 65); - - // In case of an error, try sending again - if (result < 0) - { - //printf(" ERR %u", result); - retries++; - continue; - } + memcpy(bufferOut + 1, device->request, 64); - waits = 0; + // #ifdef PK_COM_DEBUG + printf("\n * SEND "); + for (i = 0; i < 10; i++) { + printf("%X ", bufferOut[i]); + } + // #endif - // Request receiving loop - while (waits++ < 50) - { - result = hid_read(devHandle, device->response, 65); + result = hid_write(devHandle, bufferOut, 65); - // Error is not an option - if (result < 0) - { - //printf(" Receive ERR %u", result); - break; - } + // In case of an error, try sending again + if (result < 0) { + // printf(" ERR %u", result); + retries++; + continue; + } -#ifdef PK_COM_DEBUG - printf("\n * RECV "); - for (i = 0; i < 10; i++) - { - printf("%X ", device->response[i]); + waits = 0; + + // Request receiving loop + while (waits++ < 50) { + result = hid_read(devHandle, device->response, 65); + + // Error is not an option + if (result < 0) { + // printf(" Receive ERR %u", result); + break; + } + + // #ifdef PK_COM_DEBUG + printf("\n * RECV "); + for (i = 0; i < 10; i++) { + printf("%X ", device->response[i]); + } + + printf(" (request ID: %X ?= %X", device->response[6], device->requestID); + // #endif + + // Check the header and the request ID + if (device->response[0] == 0xAA && + device->response[6] == device->requestID) { + if (device->response[7] == getChecksum(device->response)) { + LastRetryCount = retries; + LastWaitCount = waits; + // This is it. Return from this function + return PK_OK; } - - printf(" (request ID: %X ?= %X", device->response[6], device->requestID); -#endif - - // Check the header and the request ID - if (device->response[0] == 0xAA && device->response[6] == device->requestID) - { - if (device->response[7] == getChecksum(device->response)) - { - LastRetryCount = retries; - LastWaitCount = waits; - // This is it. Return from this function - return PK_OK; - } - } - } + } } + } - return PK_ERR_TRANSFER; + return PK_ERR_TRANSFER; } - // ****************************************************************************************** -// These functions are used to access the device data without using the structures... +// These functions are used to access the device data without using the +// structures... // ****************************************************************************************** -void PK_SL_SetPinFunction(sPoKeysDevice* device, uint8_t pin, uint8_t function) -{ - device->Pins[pin].PinFunction = function; +void PK_SL_SetPinFunction(sPoKeysDevice *device, uint8_t pin, + uint8_t function) { + device->Pins[pin].PinFunction = function; } -uint8_t PK_SL_GetPinFunction(sPoKeysDevice* device, uint8_t pin) -{ - return device->Pins[pin].PinFunction; +uint8_t PK_SL_GetPinFunction(sPoKeysDevice *device, uint8_t pin) { + return device->Pins[pin].PinFunction; } -void PK_SL_DigitalOutputSet(sPoKeysDevice* device, uint8_t pin, uint8_t value) -{ - device->Pins[pin].DigitalValueSet = value; +void PK_SL_DigitalOutputSet(sPoKeysDevice *device, uint8_t pin, uint8_t value) { + device->Pins[pin].DigitalValueSet = value; } -uint8_t PK_SL_DigitalInputGet(sPoKeysDevice* device, uint8_t pin) -{ - return device->Pins[pin].DigitalValueGet; +uint8_t PK_SL_DigitalInputGet(sPoKeysDevice *device, uint8_t pin) { + return device->Pins[pin].DigitalValueGet; } -uint32_t PK_SL_AnalogInputGet(sPoKeysDevice* device, uint8_t pin) -{ - return device->Pins[pin].AnalogValue; +uint32_t PK_SL_AnalogInputGet(sPoKeysDevice *device, uint8_t pin) { + return device->Pins[pin].AnalogValue; } - diff --git a/lib/pokey/PoKeysLibCoreSockets.c b/lib/pokey/PoKeysLibCoreSockets.c index c6a9758..fc3d4ba 100755 --- a/lib/pokey/PoKeysLibCoreSockets.c +++ b/lib/pokey/PoKeysLibCoreSockets.c @@ -1,6 +1,6 @@ /* -Copyright (C) 2013 Matevž Bošnak (matevz@poscope.com) +Copyright (C) 2013 Matev� Bo�nak (matevz@poscope.com) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -22,846 +22,827 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "PoKeysLibCore.h" #ifdef WIN32 - #include "windows.h" - // #include "Winsock.h" - #include "conio.h" - #include +#include "windows.h" +// #include "Winsock.h" +#include "conio.h" +#include #else - #include - #include - #include - #include - #include - #include - #include +#include +#include +#include +#include +#include +#include +#include + #endif +#include "PoKeysLib.h" #include #include #include -#include "PoKeysLib.h" //#define DEBUG_PoKeysLibSockets #ifdef DEBUG_PoKeysLibSockets - #define debug_printf printf +#define debug_printf printf #else - #define debug_printf (void) +#define debug_printf (void) #endif - -// Get a list of interfaces - source: Jeremy @ http://developerweb.net/viewtopic.php?id=5085 +// Get a list of interfaces - source: Jeremy @ +// http://developerweb.net/viewtopic.php?id=5085 typedef unsigned long uint32; -#if defined(__FreeBSD__) || defined(BSD) || defined(__APPLE__) || defined(__linux__) - #define USE_GETIFADDRS 1 - #define SOCKADDR struct sockaddr +#if defined(__FreeBSD__) || defined(BSD) || defined(__APPLE__) || \ + defined(__linux__) +#define USE_GETIFADDRS 1 +#define SOCKADDR struct sockaddr - #include +#include - uint32 SockAddrToUint32(struct sockaddr * a) - { - return ((a)&&(a->sa_family == AF_INET)) ? ntohl(((struct sockaddr_in *)a)->sin_addr.s_addr) : 0; - } +uint32 SockAddrToUint32(struct sockaddr *a) { + return ((a) && (a->sa_family == AF_INET)) + ? ntohl(((struct sockaddr_in *)a)->sin_addr.s_addr) + : 0; +} #endif -uint32 * GetBroadcastAddresses() -{ - uint32 * list = malloc(sizeof(uint32) * 100); - uint32* ptr = list; +uint32 *GetBroadcastAddresses() { + uint32 *list = malloc(sizeof(uint32) * 100); + uint32 *ptr = list; #if defined(WIN32) - uint32 i; - MIB_IPADDRTABLE * ipTable = NULL; - IP_ADAPTER_INFO * pAdapterInfo = NULL; - ULONG bufLen = 0; - uint32 ipRet; - uint32 apRet; + uint32 i; + MIB_IPADDRTABLE *ipTable = NULL; + IP_ADAPTER_INFO *pAdapterInfo = NULL; + ULONG bufLen = 0; + uint32 ipRet; + uint32 apRet; - MIB_IPADDRROW * row; + MIB_IPADDRROW *row; - uint32 ipAddr; - uint32 netmask; - uint32 baddr; + uint32 ipAddr; + uint32 netmask; + uint32 baddr; #endif #if defined(USE_GETIFADDRS) - uint32 tmp; + uint32 tmp; #endif - *ptr = 0; - + *ptr = 0; #if defined(USE_GETIFADDRS) - // BSD-style implementation - struct ifaddrs * ifap; - if (getifaddrs(&ifap) == 0) - { - struct ifaddrs * p = ifap; - while(p) - { - uint32 ifaAddr = SockAddrToUint32(p->ifa_addr); - - if (ifaAddr > 0) - { - tmp = ((struct sockaddr_in *)p->ifa_broadaddr)->sin_addr.s_addr; - if (tmp) *(ptr++) = tmp; - } - p = p->ifa_next; - } - freeifaddrs(ifap); + // BSD-style implementation + struct ifaddrs *ifap; + if (getifaddrs(&ifap) == 0) { + struct ifaddrs *p = ifap; + while (p) { + uint32 ifaAddr = SockAddrToUint32(p->ifa_addr); + + if (ifaAddr > 0) { + tmp = ((struct sockaddr_in *)p->ifa_broadaddr)->sin_addr.s_addr; + if (tmp) + *(ptr++) = tmp; + } + p = p->ifa_next; } + freeifaddrs(ifap); + } #elif defined(WIN32) - // Windows XP style implementation + // Windows XP style implementation + + // Adapted from example code at + // http://msdn2.microsoft.com/en-us/library/aa365917.aspx Now get Windows' + // IPv4 addresses table. Once again, we gotta call GetIpAddrTable() multiple + // times in order to deal with potential race conditions properly. + { + for (i = 0; i < 5; i++) { + ipRet = GetIpAddrTable(ipTable, &bufLen, 0); + if (ipRet == ERROR_INSUFFICIENT_BUFFER) { + free(ipTable); // in case we had previously allocated it + ipTable = (MIB_IPADDRTABLE *)malloc(bufLen); + } else if (ipRet == NO_ERROR) + break; + else { + free(ipTable); + ipTable = NULL; + break; + } + } + } - // Adapted from example code at http://msdn2.microsoft.com/en-us/library/aa365917.aspx - // Now get Windows' IPv4 addresses table. Once again, we gotta call GetIpAddrTable() - // multiple times in order to deal with potential race conditions properly. + if (ipTable) { + // Try to get the Adapters-info table, so we can given useful names to the + // IP addresses we are returning. Gotta call GetAdaptersInfo() up to 5 + // times to handle the potential race condition between the size-query call + // and the get-data call. I love a well-designed API :^P { - for (i=0; i<5; i++) - { - ipRet = GetIpAddrTable(ipTable, &bufLen, 0); - if (ipRet == ERROR_INSUFFICIENT_BUFFER) - { - free(ipTable); // in case we had previously allocated it - ipTable = (MIB_IPADDRTABLE *) malloc(bufLen); - } - else if (ipRet == NO_ERROR) break; - else - { - free(ipTable); - ipTable = NULL; - break; - } - } - } - - if (ipTable) - { - // Try to get the Adapters-info table, so we can given useful names to the IP - // addresses we are returning. Gotta call GetAdaptersInfo() up to 5 times to handle - // the potential race condition between the size-query call and the get-data call. - // I love a well-designed API :^P - { - for (i=0; i<5; i++) - { - apRet = GetAdaptersInfo(pAdapterInfo, &bufLen); - if (apRet == ERROR_BUFFER_OVERFLOW) - { - free(pAdapterInfo); // in case we had previously allocated it - pAdapterInfo = (IP_ADAPTER_INFO *) malloc(bufLen); - } - else if (apRet == ERROR_SUCCESS) break; - else - { - free(pAdapterInfo); - pAdapterInfo = NULL; - break; - } - } + for (i = 0; i < 5; i++) { + apRet = GetAdaptersInfo(pAdapterInfo, &bufLen); + if (apRet == ERROR_BUFFER_OVERFLOW) { + free(pAdapterInfo); // in case we had previously allocated it + pAdapterInfo = (IP_ADAPTER_INFO *)malloc(bufLen); + } else if (apRet == ERROR_SUCCESS) + break; + else { + free(pAdapterInfo); + pAdapterInfo = NULL; + break; + } } + } - for (i=0; i < ipTable->dwNumEntries; i++) - { - // ----------------------------------------------------------------------------------------- - row = &ipTable->table[i]; - // ----------------------------------------------------------------------------------------- + for (i = 0; i < ipTable->dwNumEntries; i++) { + // ----------------------------------------------------------------------------------------- + row = &ipTable->table[i]; + // ----------------------------------------------------------------------------------------- - ipAddr = (row->dwAddr); - netmask = (row->dwMask); - baddr = ipAddr & netmask; - if (row->dwBCastAddr) baddr |= ~netmask; + ipAddr = (row->dwAddr); + netmask = (row->dwMask); + baddr = ipAddr & netmask; + if (row->dwBCastAddr) + baddr |= ~netmask; - if (baddr) *(ptr++) = baddr; - } + if (baddr) + *(ptr++) = baddr; + } - free(pAdapterInfo); - free(ipTable); - } + free(pAdapterInfo); + free(ipTable); + } #else - // Dunno what we're running on here! -# error "Don't know how to implement GetBroadcastAddresses() on this OS!" +// Dunno what we're running on here! +#error "Don't know how to implement GetBroadcastAddresses() on this OS!" #endif - *ptr = 0; - return list; + *ptr = 0; + return list; } #ifdef WIN32 - WSADATA wsaData; - - int32_t InitWinsock() - { - // Initialize Winsock - version 2.2 - if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) - { - debug_printf("Winsock startup failed!\n"); - return -1; - } - return 0; - } +WSADATA wsaData; + +int32_t InitWinsock() { + // Initialize Winsock - version 2.2 + if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { + debug_printf("Winsock startup failed!\n"); + return -1; + } + return 0; +} - int32_t TerminateWinsock() - { - WSACleanup(); - return 0; - } +int32_t TerminateWinsock() { + WSACleanup(); + return 0; +} #endif - -int32_t PK_EnumerateNetworkDevices(sPoKeysNetworkDeviceSummary * devices, uint32_t timeout) -{ - return PK_SearchNetworkDevices(devices, timeout, 0); +int32_t PK_EnumerateNetworkDevices(sPoKeysNetworkDeviceSummary *devices, + uint32_t timeout) { + return PK_SearchNetworkDevices(devices, timeout, 0); } -int32_t PK_SearchNetworkDevices(sPoKeysNetworkDeviceSummary * devices, uint32_t timeout, uint32_t serialNumberToFind) -{ - //Broadcast the message - int32_t t; // 100 ms timeout +int32_t PK_SearchNetworkDevices(sPoKeysNetworkDeviceSummary *devices, + uint32_t timeout, uint32_t serialNumberToFind) { + // Broadcast the message + int32_t t; // 100 ms timeout #ifdef WIN32 - struct sockaddr_in remoteEP; - SOCKET txSocket; + struct sockaddr_in remoteEP; + SOCKET txSocket; #else - int txSocket; - struct sockaddr_in remoteEP; - fd_set fds; - struct timeval stimeout; + int txSocket; + struct sockaddr_in remoteEP; + fd_set fds; + struct timeval stimeout; #endif - int UDPbroadcast = 1; - int status = 0; - int BufLen = 0; - char SendBuf[1]; - uint32 * addr; - uint32 * addrPtr; - uint32 a; - unsigned char rcvbuf[500]; - int nrOfDetectedBoards = 0; - sPoKeysNetworkDeviceSummary * device; + int UDPbroadcast = 1; + int status = 0; + int BufLen = 0; + char SendBuf[1]; + uint32 *addr; + uint32 *addrPtr; + uint32 a; + unsigned char rcvbuf[500]; + int nrOfDetectedBoards = 0; + sPoKeysNetworkDeviceSummary *device; - t = timeout; + t = timeout; - debug_printf("Enumerating network PoKeys devices...\n"); + debug_printf("Enumerating network PoKeys devices...\n"); #ifdef WIN32 - if (InitWinsock() != 0) - { - debug_printf("InitWinsock error!"); - return 0; - } + if (InitWinsock() != 0) { + debug_printf("InitWinsock error!"); + return 0; + } #endif - - // Create socket for discovery packet - if ((txSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) - { - debug_printf("Error creating socket\n"); - return 0; - } - if (setsockopt( txSocket, SOL_SOCKET, SO_BROADCAST, (char *)&UDPbroadcast, sizeof UDPbroadcast) == -1) - { - debug_printf("Error setting broadcast option\n"); - return 0; - } + + // Create socket for discovery packet + if ((txSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { + debug_printf("Error creating socket\n"); + return 0; + } + if (setsockopt(txSocket, SOL_SOCKET, SO_BROADCAST, (char *)&UDPbroadcast, + sizeof UDPbroadcast) == -1) { + debug_printf("Error setting broadcast option\n"); + return 0; + } #ifdef WIN32 - if (setsockopt( txSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&t, sizeof(t)) == -1) - { - debug_printf("Error setting SO_RCVTIMEO option\n"); - return 0; - } - if (setsockopt( txSocket, SOL_SOCKET, SO_SNDTIMEO, (char *)&t, sizeof(t)) == -1) - { - debug_printf("Error setting SO_SNDTIMEO option\n"); - return 0; - } + if (setsockopt(txSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&t, sizeof(t)) == + -1) { + debug_printf("Error setting SO_RCVTIMEO option\n"); + return 0; + } + if (setsockopt(txSocket, SOL_SOCKET, SO_SNDTIMEO, (char *)&t, sizeof(t)) == + -1) { + debug_printf("Error setting SO_SNDTIMEO option\n"); + return 0; + } #endif + debug_printf("Sending discovery request...\n"); - debug_printf("Sending discovery request...\n"); + addr = GetBroadcastAddresses(); + addrPtr = addr; - addr = GetBroadcastAddresses(); - addrPtr = addr; + while (*addr) { + a = *addr; + debug_printf("Sending request to %d.%d.%d.%d... ", (a & 0xFF), + (a >> 8) & 0xFF, (a >> 16) & 0xFF, (a >> 24) & 0xFF); - while(*addr) - { - a = *addr; - debug_printf("Sending request to %d.%d.%d.%d... ", (a&0xFF),(a>>8)&0xFF, (a>>16)&0xFF, (a>>24)&0xFF); + // Send discovery request... + remoteEP.sin_family = AF_INET; + remoteEP.sin_port = htons(20055); + remoteEP.sin_addr.s_addr = a; // inet_addr("255.255.255.255"); - // Send discovery request... - remoteEP.sin_family = AF_INET; - remoteEP.sin_port = htons(20055); - remoteEP.sin_addr.s_addr = a; // inet_addr("255.255.255.255"); - - if (sendto(txSocket, SendBuf, BufLen, 0, (SOCKADDR *)&remoteEP, sizeof(remoteEP)) == -1) - { - debug_printf("Failed\n"); + if (sendto(txSocket, SendBuf, BufLen, 0, (SOCKADDR *)&remoteEP, + sizeof(remoteEP)) == -1) { + debug_printf("Failed\n"); #ifdef WIN32 - closesocket(txSocket); - WSACleanup(); + closesocket(txSocket); + WSACleanup(); #else - close(txSocket); + close(txSocket); #endif - return 0; - } - debug_printf(" done\n"); - addr++; + return 0; } - free(addrPtr); - - - debug_printf("Waiting for responses...\n"); - + debug_printf(" done\n"); + addr++; + } + free(addrPtr); + debug_printf("Waiting for responses...\n"); #ifdef WIN32 #else - // Wait for discovery response... - stimeout.tv_sec = 0; - stimeout.tv_usec = 1000 * timeout; + // Wait for discovery response... + stimeout.tv_sec = 0; + stimeout.tv_usec = 1000 * timeout; - FD_ZERO(&fds); - FD_SET(txSocket, &fds); + FD_ZERO(&fds); + FD_SET(txSocket, &fds); #endif - - while(nrOfDetectedBoards < 16) - { - // Receive response from devices + while (nrOfDetectedBoards < 16) { +// Receive response from devices #ifdef WIN32 #else - if (select(txSocket + 1, &fds, NULL, NULL, &stimeout) < 0) - { - debug_printf("Error in select...\n"); - close(txSocket); - return 0; - } + if (select(txSocket + 1, &fds, NULL, NULL, &stimeout) < 0) { + debug_printf("Error in select...\n"); + close(txSocket); + return 0; + } - if (FD_ISSET(txSocket, &fds) == 0) break; + if (FD_ISSET(txSocket, &fds) == 0) + break; #endif - debug_printf("Retrieving data...\n"); - status = recv(txSocket, (char *)rcvbuf, sizeof(rcvbuf), 0); - - if (status < 0) - { - debug_printf("Error receiving data...\n"); - break; - } - - // Get IP address and receive message - if (status > 0) - { - if (status == 14) - { - // Parse the response - debug_printf("Received response...\n"); - - debug_printf(" User ID: %u\n", rcvbuf[0]); - debug_printf(" Serial: %u\n", (int)(256 * (int)rcvbuf[1] + rcvbuf[2])); - debug_printf(" Version: %u.%u\n", rcvbuf[3], rcvbuf[4]); - debug_printf(" IP address: %u.%u.%u.%u\n", rcvbuf[5], rcvbuf[6], rcvbuf[7], rcvbuf[8]); - debug_printf(" DHCP: %u\n", rcvbuf[9]); - debug_printf(" Host IP address: %u.%u.%u.%u\n", rcvbuf[10], rcvbuf[11], rcvbuf[12], rcvbuf[13]); - - // Save the device info - device = &devices[nrOfDetectedBoards]; - //device->userID = rcvbuf[0]; - device->SerialNumber = (int)(256 * (int)rcvbuf[1] + rcvbuf[2]); - device->FirmwareVersionMajor = rcvbuf[3]; - device->FirmwareVersionMinor = rcvbuf[4]; - memcpy(device->IPaddress, rcvbuf + 5, 4); - device->DHCP = rcvbuf[9]; - memcpy(device->hostIP, rcvbuf + 10, 4); - device->HWtype = 0; - - nrOfDetectedBoards++; - status = 0; - - if (serialNumberToFind == device->SerialNumber) break; - } else if (status == 19) - { - // Parse the response - debug_printf("Received response from 58 series device...\n"); - - // Save the device info - device = &devices[nrOfDetectedBoards]; - //device->userID = rcvbuf[0]; - device->SerialNumber = (int)rcvbuf[14] + ((int)rcvbuf[15] << 8) + ((int)rcvbuf[16] << 16) + ((int)rcvbuf[17] << 24); - device->FirmwareVersionMajor = rcvbuf[3]; - device->FirmwareVersionMinor = rcvbuf[4]; - memcpy(device->IPaddress, rcvbuf + 5, 4); - device->DHCP = rcvbuf[9]; - memcpy(device->hostIP, rcvbuf + 10, 4); - device->HWtype = rcvbuf[18]; - - debug_printf(" User ID: %u\n", rcvbuf[0]); - debug_printf(" Serial: %u\n", device->SerialNumber); - debug_printf(" Version: %u.%u\n", rcvbuf[3], rcvbuf[4]); - debug_printf(" IP address: %u.%u.%u.%u\n", rcvbuf[5], rcvbuf[6], rcvbuf[7], rcvbuf[8]); - debug_printf(" DHCP: %u\n", rcvbuf[9]); - debug_printf(" Host IP address: %u.%u.%u.%u\n", rcvbuf[10], rcvbuf[11], rcvbuf[12], rcvbuf[13]); - - nrOfDetectedBoards++; - status = 0; - - if (serialNumberToFind == device->SerialNumber) break; - } - } - else - { - if (nrOfDetectedBoards == 0) - { - debug_printf("\n No Boards detected\n"); - } - } - + debug_printf("Retrieving data...\n"); + status = recv(txSocket, (char *)rcvbuf, sizeof(rcvbuf), 0); + if (status < 0) { + debug_printf("Error receiving data...\n"); + break; } + // Get IP address and receive message + if (status > 0) { + if (status == 14) { + // Parse the response + debug_printf("Received response...\n"); + + debug_printf(" User ID: %u\n", rcvbuf[0]); + debug_printf(" Serial: %u\n", (int)(256 * (int)rcvbuf[1] + rcvbuf[2])); + debug_printf(" Version: %u.%u\n", rcvbuf[3], rcvbuf[4]); + debug_printf(" IP address: %u.%u.%u.%u\n", rcvbuf[5], rcvbuf[6], + rcvbuf[7], rcvbuf[8]); + debug_printf(" DHCP: %u\n", rcvbuf[9]); + debug_printf(" Host IP address: %u.%u.%u.%u\n", rcvbuf[10], rcvbuf[11], + rcvbuf[12], rcvbuf[13]); + + // Save the device info + device = &devices[nrOfDetectedBoards]; + // device->userID = rcvbuf[0]; + device->SerialNumber = (int)(256 * (int)rcvbuf[1] + rcvbuf[2]); + device->FirmwareVersionMajor = rcvbuf[3]; + device->FirmwareVersionMinor = rcvbuf[4]; + memcpy(device->IPaddress, rcvbuf + 5, 4); + device->DHCP = rcvbuf[9]; + memcpy(device->hostIP, rcvbuf + 10, 4); + device->HWtype = 0; + + nrOfDetectedBoards++; + status = 0; + + if (serialNumberToFind == device->SerialNumber) + break; + } else if (status == 19) { + // Parse the response + debug_printf("Received response from 58 series device...\n"); + + // Save the device info + device = &devices[nrOfDetectedBoards]; + // device->userID = rcvbuf[0]; + device->SerialNumber = (int)rcvbuf[14] + ((int)rcvbuf[15] << 8) + + ((int)rcvbuf[16] << 16) + + ((int)rcvbuf[17] << 24); + device->FirmwareVersionMajor = rcvbuf[3]; + device->FirmwareVersionMinor = rcvbuf[4]; + memcpy(device->IPaddress, rcvbuf + 5, 4); + device->DHCP = rcvbuf[9]; + memcpy(device->hostIP, rcvbuf + 10, 4); + device->HWtype = rcvbuf[18]; + + debug_printf(" User ID: %u\n", rcvbuf[0]); + debug_printf(" Serial: %u\n", device->SerialNumber); + debug_printf(" Version: %u.%u\n", rcvbuf[3], rcvbuf[4]); + debug_printf(" IP address: %u.%u.%u.%u\n", rcvbuf[5], rcvbuf[6], + rcvbuf[7], rcvbuf[8]); + debug_printf(" DHCP: %u\n", rcvbuf[9]); + debug_printf(" Host IP address: %u.%u.%u.%u\n", rcvbuf[10], rcvbuf[11], + rcvbuf[12], rcvbuf[13]); + + nrOfDetectedBoards++; + status = 0; + + if (serialNumberToFind == device->SerialNumber) + break; + } + } else { + if (nrOfDetectedBoards == 0) { + debug_printf("\n No Boards detected\n"); + } + } + } #ifdef WIN32 - closesocket(txSocket); + closesocket(txSocket); #else - close(txSocket); + close(txSocket); #endif - return nrOfDetectedBoards; + return nrOfDetectedBoards; } -sPoKeysDevice* PK_ConnectToNetworkDevice(sPoKeysNetworkDeviceSummary * device) -{ - int result; +sPoKeysDevice *PK_ConnectToNetworkDevice(sPoKeysNetworkDeviceSummary *device) { + int result; #ifdef WIN32 - int t = 100; // 100 ms timeout + int t = 100; // 100 ms timeout #endif - // Create target endpoint - //struct sockaddr_in * remoteEP; - uint32 addr ; - - // Create temporary device object - sPoKeysDevice * tmpDevice; + // Create target endpoint + // struct sockaddr_in * remoteEP; + uint32 addr; - if (device == NULL) return NULL; + // Create temporary device object + sPoKeysDevice *tmpDevice; - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - tmpDevice->devHandle2 = malloc(sizeof(struct sockaddr_in)); + if (device == NULL) + return NULL; - tmpDevice->connectionType = PK_DeviceType_NetworkDevice; // Network device - tmpDevice->connectionParam = device->useUDP; + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); + tmpDevice->devHandle2 = malloc(sizeof(struct sockaddr_in)); - addr = (uint32)device->IPaddress[0] + ((uint32)device->IPaddress[1] << 8) + ((uint32)device->IPaddress[2] << 16) + ((uint32)device->IPaddress[3] << 24); - // Set up the RecvAddr structure with the broadcast ip address and correct port number - ((struct sockaddr_in*)tmpDevice->devHandle2)->sin_family = AF_INET; - ((struct sockaddr_in*)tmpDevice->devHandle2)->sin_port = htons(20055); - ((struct sockaddr_in*)tmpDevice->devHandle2)->sin_addr.s_addr = addr; + tmpDevice->connectionType = PK_DeviceType_NetworkDevice; // Network device + tmpDevice->connectionParam = device->useUDP; -#ifdef WIN32 - if (InitWinsock() != 0) - { - debug_printf("InitWinsock error!"); - return 0; - } + addr = (uint32)device->IPaddress[0] + ((uint32)device->IPaddress[1] << 8) + + ((uint32)device->IPaddress[2] << 16) + + ((uint32)device->IPaddress[3] << 24); + // Set up the RecvAddr structure with the broadcast ip address and correct + // port number + ((struct sockaddr_in *)tmpDevice->devHandle2)->sin_family = AF_INET; + ((struct sockaddr_in *)tmpDevice->devHandle2)->sin_port = htons(20055); + ((struct sockaddr_in *)tmpDevice->devHandle2)->sin_addr.s_addr = addr; +#ifdef WIN32 + if (InitWinsock() != 0) { + debug_printf("InitWinsock error!"); + return 0; + } + + if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) { + tmpDevice->devHandle = (void *)socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + } else { + tmpDevice->devHandle = (void *)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + } + + if ((SOCKET)tmpDevice->devHandle == -1) +#else + tmpDevice->devHandle = malloc(sizeof(int)); + if (tmpDevice->devHandle == NULL) + return NULL; - if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) - { - tmpDevice->devHandle = (void*)socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - } else - { - tmpDevice->devHandle = (void*)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - } + if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) + *(int *)tmpDevice->devHandle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + else + *(int *)tmpDevice->devHandle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if ((SOCKET)tmpDevice->devHandle == -1) -#else - tmpDevice->devHandle = malloc(sizeof(int)); - if (tmpDevice->devHandle == NULL) return NULL; - - if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) - *(int *)tmpDevice->devHandle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - else - *(int *)tmpDevice->devHandle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - - if ((*(int *)tmpDevice->devHandle) == -1) + if ((*(int *)tmpDevice->devHandle) == -1) #endif - { - //CleanDevice(tmpDevice); + { +// CleanDevice(tmpDevice); #ifndef WIN32 - free(tmpDevice->devHandle); + free(tmpDevice->devHandle); #endif - free(tmpDevice); + free(tmpDevice); - return NULL; // Couldn't create the socket - } + return NULL; // Couldn't create the socket + } #ifdef WIN32 - // Set socket options - setsockopt((SOCKET)tmpDevice->devHandle, SOL_SOCKET, SO_RCVTIMEO, (char *)&t, sizeof(t)); - setsockopt((SOCKET)tmpDevice->devHandle, SOL_SOCKET, SO_SNDTIMEO, (char *)&t, sizeof(t)); + // Set socket options + setsockopt((SOCKET)tmpDevice->devHandle, SOL_SOCKET, SO_RCVTIMEO, (char *)&t, + sizeof(t)); + setsockopt((SOCKET)tmpDevice->devHandle, SOL_SOCKET, SO_SNDTIMEO, (char *)&t, + sizeof(t)); #endif - - // Connect to target IP +// Connect to target IP #ifdef WIN32 - if (tmpDevice->connectionParam != PK_ConnectionParam_UDP) - result = connect((SOCKET)tmpDevice->devHandle, (SOCKADDR *)tmpDevice->devHandle2, sizeof(struct sockaddr_in)); - else - result = 0; + if (tmpDevice->connectionParam != PK_ConnectionParam_UDP) + result = + connect((SOCKET)tmpDevice->devHandle, (SOCKADDR *)tmpDevice->devHandle2, + sizeof(struct sockaddr_in)); + else + result = 0; #else - result = 0; - if (tmpDevice->connectionParam != PK_ConnectionParam_UDP) - result = connect(*(int *)tmpDevice->devHandle, (struct sockaddr *)tmpDevice->devHandle2, sizeof(struct sockaddr_in)); - else - result = 0; - + result = 0; + if (tmpDevice->connectionParam != PK_ConnectionParam_UDP) + result = connect(*(int *)tmpDevice->devHandle, + (struct sockaddr *)tmpDevice->devHandle2, + sizeof(struct sockaddr_in)); + else + result = 0; + #endif - if (result == -1) - { - debug_printf(" ERROR"); - //CleanDevice(tmpDevice); + if (result == -1) { + debug_printf(" ERROR"); +// CleanDevice(tmpDevice); #ifdef WIN32 - closesocket((SOCKET)tmpDevice->devHandle); + closesocket((SOCKET)tmpDevice->devHandle); #else - close(*(int *)tmpDevice->devHandle); - free(tmpDevice->devHandle); + close(*(int *)tmpDevice->devHandle); + free(tmpDevice->devHandle); #endif - free(tmpDevice); + free(tmpDevice); - return NULL; // Couldn't connect - } + return NULL; // Couldn't connect + } #ifdef WIN32 - if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) - { - // Setup socket to be unblocking - u_long iMode = TRUE; - ioctlsocket((SOCKET)tmpDevice->devHandle, FIONBIO, &iMode); - } + if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) { + // Setup socket to be unblocking + u_long iMode = TRUE; + ioctlsocket((SOCKET)tmpDevice->devHandle, FIONBIO, &iMode); + } #endif - debug_printf(" Connected\n"); + debug_printf(" Connected\n"); - debug_printf("Initializing the device object... "); - InitializeNewDevice(tmpDevice); - debug_printf("done\n"); + debug_printf("Initializing the device object... "); + InitializeNewDevice(tmpDevice); + debug_printf("done\n"); - - //printf("Connected to PoKeys device at %s", addrBuf); - return tmpDevice; + // printf("Connected to PoKeys device at %s", addrBuf); + return tmpDevice; } -void PK_DisconnectNetworkDevice(sPoKeysDevice* device) -{ - if (device == NULL) return; - if (device->connectionType != PK_DeviceType_NetworkDevice) return; +void PK_DisconnectNetworkDevice(sPoKeysDevice *device) { + if (device == NULL) + return; + if (device->connectionType != PK_DeviceType_NetworkDevice) + return; - debug_printf("\nClosing connection..."); + debug_printf("\nClosing connection..."); #ifdef WIN32 - if ((SOCKET)device->devHandle) - closesocket((SOCKET)device->devHandle); + if ((SOCKET)device->devHandle) + closesocket((SOCKET)device->devHandle); #else - close(*(int *)device->devHandle); - free(device->devHandle); + close(*(int *)device->devHandle); + free(device->devHandle); #endif - // Release secondary device handle - if (device->devHandle2) - free(device->devHandle2); + // Release secondary device handle + if (device->devHandle2) + free(device->devHandle2); } +int32_t SendEthRequest(sPoKeysDevice *device) { + uint32_t retries1 = 0; + uint32_t retries2 = 0; + int result; -int32_t SendEthRequest(sPoKeysDevice* device) -{ - uint32_t retries1 = 0; - uint32_t retries2 = 0; - int result; - - fd_set fds; - struct timeval stimeout; + fd_set fds; + struct timeval stimeout; - if (device == NULL) return PK_ERR_GENERIC; - if (device->connectionType != PK_DeviceType_NetworkDevice) return PK_ERR_GENERIC; - if (device->devHandle == NULL) return PK_ERR_GENERIC; + if (device == NULL) + return PK_ERR_GENERIC; + if (device->connectionType != PK_DeviceType_NetworkDevice) + return PK_ERR_GENERIC; + if (device->devHandle == NULL) + return PK_ERR_GENERIC; - while (1) - { - // Form the request packet - device->requestID++; + while (1) { + // Form the request packet + device->requestID++; - device->request[0] = 0xBB; - device->request[6] = device->requestID; - device->request[7] = getChecksum(device->request); + device->request[0] = 0xBB; + device->request[6] = device->requestID; + device->request[7] = getChecksum(device->request); - //memcpy(requestBuffer, device->request, 64); + // memcpy(requestBuffer, device->request, 64); - debug_printf("\nSending..."); - // Send the data + debug_printf("\nSending..."); + // Send the data - if (device->connectionParam == PK_ConnectionParam_UDP) - { + if (device->connectionParam == PK_ConnectionParam_UDP) { #ifdef WIN32 - if (sendto((SOCKET)device->devHandle, (char *)device->request, 64, 0, (SOCKADDR *)device->devHandle2, sizeof(struct sockaddr_in)) == -1) + if (sendto((SOCKET)device->devHandle, (char *)device->request, 64, 0, + (SOCKADDR *)device->devHandle2, + sizeof(struct sockaddr_in)) == -1) #else - if (sendto(*(int*)device->devHandle, (char *)device->request, 64, 0, (SOCKADDR *)device->devHandle2, sizeof(struct sockaddr_in)) == -1) + if (sendto(*(int *)device->devHandle, (char *)device->request, 64, 0, + (SOCKADDR *)device->devHandle2, + sizeof(struct sockaddr_in)) == -1) #endif - { - debug_printf("Error sending UDP report\nAborting...\n"); - return -1; - } - } else - { + { + debug_printf("Error sending UDP report\nAborting...\n"); + return -1; + } + } else { #ifdef WIN32 - if (send((SOCKET)device->devHandle, (char *)device->request, 64, 0) != 64) + if (send((SOCKET)device->devHandle, (char *)device->request, 64, 0) != 64) #else - if (send(*(int*)device->devHandle, (char *)device->request, 64, 0) != 64) + if (send(*(int *)device->devHandle, (char *)device->request, 64, 0) != 64) #endif - { - debug_printf("Error sending TCP report\nAborting...\n"); - return -1; - } - } + { + debug_printf("Error sending TCP report\nAborting...\n"); + return -1; + } + } - // Wait for the response - while(1) - { + // Wait for the response + while (1) { #ifdef WIN32 - FD_ZERO(&fds); - FD_SET((SOCKET)device->devHandle, &fds); - - stimeout.tv_sec = 0; - stimeout.tv_usec = 1000 * device->socketTimeout; - - result = select((SOCKET)device->devHandle + 1, &fds, NULL, NULL, &stimeout); - - if (result == 0 || result == -1) - { - // Timeout... - debug_printf("Timeout!"); - if (++retries1 > device->readRetries) break; - continue; - } - - //device->reserved64 = GetTickCount64(); - result = recv((SOCKET)device->devHandle, (char *)device->response, 64, 0); - //device->reserved64 = GetTickCount64() - device->reserved64; - //printf("Time: %u\n", (uint32_t)device->reserved64); + FD_ZERO(&fds); + FD_SET((SOCKET)device->devHandle, &fds); + + stimeout.tv_sec = 0; + stimeout.tv_usec = 1000 * device->socketTimeout; + + result = + select((SOCKET)device->devHandle + 1, &fds, NULL, NULL, &stimeout); + + if (result == 0 || result == -1) { + // Timeout... + debug_printf("Timeout!"); + if (++retries1 > device->readRetries) + break; + continue; + } + + // device->reserved64 = GetTickCount64(); + result = recv((SOCKET)device->devHandle, (char *)device->response, 64, 0); +// device->reserved64 = GetTickCount64() - device->reserved64; +// printf("Time: %u\n", (uint32_t)device->reserved64); #else - FD_ZERO(&fds); - FD_SET(*(int*)device->devHandle, &fds); + FD_ZERO(&fds); + FD_SET(*(int *)device->devHandle, &fds); + + stimeout.tv_sec = 0; - stimeout.tv_sec = 0; - stimeout.tv_usec = 1000 * device->socketTimeout; + stimeout.tv_usec = 1000 * device->socketTimeout; - result = select(*(int*)device->devHandle + 1, &fds, NULL, NULL, &stimeout); + result = + select(*(int *)device->devHandle + 1, &fds, NULL, NULL, &stimeout); - if (result == 0 || result == -1) - { - // Timeout... - debug_printf("Timeout!"); - if (++retries1 > 10) break; - continue; - } + if (result == 0 || result == -1) { + // Timeout... + debug_printf("Timeout!"); + if (++retries1 > 10) + break; + continue; + } - //if (FD_ISSET(*(int*)device->devHandle, &fds) == 0) + // if (FD_ISSET(*(int*)device->devHandle, &fds) == 0) - result = recv(*(int*)device->devHandle, (char *)device->response, 64, 0); + result = recv(*(int *)device->devHandle, (char *)device->response, 64, 0); #endif - // 64 bytes received? - if (result == 64) - { - if (device->response[0] == 0xAA && device->response[6] == device->requestID) - { - if (device->response[7] == getChecksum(device->response)) - { - debug_printf(" Received!"); - return PK_OK; - } else - { - debug_printf("!! Wrong checksum..."); - } - } else - { - debug_printf("!! Wrong response received!"); - break; - } - } - else if (result == 0) - debug_printf("Connection closed\n"); - else + // 64 bytes received? + if (result == 64) { + if (device->response[0] == 0xAA && + device->response[6] == device->requestID) { + if (device->response[7] == getChecksum(device->response)) { + debug_printf(" Received!"); + return PK_OK; + } else { + debug_printf("!! Wrong checksum..."); + } + } else { + debug_printf("!! Wrong response received!"); + break; + } + } else if (result == 0) + debug_printf("Connection closed\n"); + else #ifdef WIN32 - debug_printf("recv failed: %d\n", WSAGetLastError()); + debug_printf("recv failed: %d\n", WSAGetLastError()); #else - debug_printf("recv failed\n"); + debug_printf("recv failed\n"); #endif - - if (++retries1 > device->readRetries) break; - } - - if (retries2++ > device->sendRetries) break; + if (++retries1 > device->readRetries) + break; } - debug_printf("Error - timeout..."); - return PK_ERR_TRANSFER; + if (retries2++ > device->sendRetries) + break; + } + debug_printf("Error - timeout..."); + return PK_ERR_TRANSFER; } -int32_t SendEthRequestBig(sPoKeysDevice* device) -{ - uint32_t retries1 = 0; - uint32_t retries2 = 0; - int result; - uint32_t i; +int32_t SendEthRequestBig(sPoKeysDevice *device) { + uint32_t retries1 = 0; + uint32_t retries2 = 0; + int result; + uint32_t i; - fd_set fds; - struct timeval stimeout; + fd_set fds; + struct timeval stimeout; - uint8_t * requestBuffer; - uint8_t * requestBufferPtr = 0; + uint8_t *requestBuffer; + uint8_t *requestBufferPtr = 0; - if (device == NULL) return PK_ERR_GENERIC; - if (device->connectionType != PK_DeviceType_NetworkDevice) return PK_ERR_GENERIC; - if (device->devHandle == NULL) return PK_ERR_GENERIC; + if (device == NULL) + return PK_ERR_GENERIC; + if (device->connectionType != PK_DeviceType_NetworkDevice) + return PK_ERR_GENERIC; + if (device->devHandle == NULL) + return PK_ERR_GENERIC; - if (device->multiPartBuffer == 0) return PK_ERR_GENERIC; - requestBuffer = device->multiPartBuffer; + if (device->multiPartBuffer == 0) + return PK_ERR_GENERIC; + requestBuffer = device->multiPartBuffer; - while (1) - { - // Form the request packet - for (i = 0; i < 8; i++) - { - requestBufferPtr = &requestBuffer[i * 64]; + while (1) { + // Form the request packet + for (i = 0; i < 8; i++) { + requestBufferPtr = &requestBuffer[i * 64]; - memcpy(requestBufferPtr, device->request, 8); - requestBufferPtr[0] = 0xBB; + memcpy(requestBufferPtr, device->request, 8); + requestBufferPtr[0] = 0xBB; - // Put packet ID and flags here... - requestBufferPtr[2] = i; - if (i == 0) - requestBufferPtr[2] |= (1<<3); - else if (i == 7) - requestBufferPtr[2] |= (1<<4); + // Put packet ID and flags here... + requestBufferPtr[2] = i; + if (i == 0) + requestBufferPtr[2] |= (1 << 3); + else if (i == 7) + requestBufferPtr[2] |= (1 << 4); - requestBufferPtr[6] = ++device->requestID; - requestBufferPtr[7] = getChecksum(requestBufferPtr); + requestBufferPtr[6] = ++device->requestID; + requestBufferPtr[7] = getChecksum(requestBufferPtr); - memcpy(requestBufferPtr + 8, device->multiPartData + i*56, 56); - } + memcpy(requestBufferPtr + 8, device->multiPartData + i * 56, 56); + } - debug_printf("\nSending..."); - // Send the data + debug_printf("\nSending..."); + // Send the data - if (device->connectionParam == PK_ConnectionParam_UDP) - { + if (device->connectionParam == PK_ConnectionParam_UDP) { #ifdef WIN32 - if (sendto((SOCKET)device->devHandle, (char *)requestBuffer, 512, 0, (SOCKADDR *)device->devHandle2, sizeof(struct sockaddr_in)) == -1) + if (sendto((SOCKET)device->devHandle, (char *)requestBuffer, 512, 0, + (SOCKADDR *)device->devHandle2, + sizeof(struct sockaddr_in)) == -1) #else - if (sendto(*(int*)device->devHandle, (char *)requestBuffer, 512, 0, (SOCKADDR *)device->devHandle2, sizeof(struct sockaddr_in)) == -1) + if (sendto(*(int *)device->devHandle, (char *)requestBuffer, 512, 0, + (SOCKADDR *)device->devHandle2, + sizeof(struct sockaddr_in)) == -1) #endif - { - debug_printf("Error sending UDP report\nAborting...\n"); - return -1; - } - } else - { + { + debug_printf("Error sending UDP report\nAborting...\n"); + return -1; + } + } else { #ifdef WIN32 - if (send((SOCKET)device->devHandle, (char *)requestBuffer, 512, 0) != 512) + if (send((SOCKET)device->devHandle, (char *)requestBuffer, 512, 0) != 512) #else - if (send(*(int*)device->devHandle, (char *)requestBuffer, 512, 0) != 512) + if (send(*(int *)device->devHandle, (char *)requestBuffer, 512, 0) != 512) #endif - { - debug_printf("Error sending TCP report\nAborting...\n"); - return -1; - } - } + { + debug_printf("Error sending TCP report\nAborting...\n"); + return -1; + } + } - // Wait for the response - while(1) - { + // Wait for the response + while (1) { #ifdef WIN32 - FD_ZERO(&fds); - FD_SET((SOCKET)device->devHandle, &fds); + FD_ZERO(&fds); + FD_SET((SOCKET)device->devHandle, &fds); - stimeout.tv_sec = 0; - stimeout.tv_usec = 1000 * device->socketTimeout; + stimeout.tv_sec = 0; + stimeout.tv_usec = 1000 * device->socketTimeout; - result = select((SOCKET)device->devHandle + 1, &fds, NULL, NULL, &stimeout); + result = + select((SOCKET)device->devHandle + 1, &fds, NULL, NULL, &stimeout); - if (result == 0 || result == -1) - { - // Timeout... - debug_printf("Timeout!"); - if (++retries1 > device->readRetries) break; - continue; - } + if (result == 0 || result == -1) { + // Timeout... + debug_printf("Timeout!"); + if (++retries1 > device->readRetries) + break; + continue; + } - result = recv((SOCKET)device->devHandle, (char *)device->response, 64, 0); + result = recv((SOCKET)device->devHandle, (char *)device->response, 64, 0); #else - FD_ZERO(&fds); - FD_SET(*(int*)device->devHandle, &fds); + FD_ZERO(&fds); + FD_SET(*(int *)device->devHandle, &fds); - stimeout.tv_sec = 0; - stimeout.tv_usec = 1000 * device->socketTimeout; + stimeout.tv_sec = 0; + stimeout.tv_usec = 1000 * device->socketTimeout; - result = select(*(int*)device->devHandle + 1, &fds, NULL, NULL, &stimeout); + result = + select(*(int *)device->devHandle + 1, &fds, NULL, NULL, &stimeout); - if (result == 0 || result == -1) - { - // Timeout... - debug_printf("Timeout!"); - if (++retries1 > 10) break; - continue; - } + if (result == 0 || result == -1) { + // Timeout... + debug_printf("Timeout!"); + if (++retries1 > 10) + break; + continue; + } - result = recv(*(int*)device->devHandle, (char *)device->response, 64, 0); + result = recv(*(int *)device->devHandle, (char *)device->response, 64, 0); #endif - // 64 bytes received? - if (result == 64) - { - if (device->response[0] == 0xAA && device->response[6] == device->requestID) - { - if (device->response[7] == getChecksum(device->response)) - { - debug_printf(" Received!"); - return PK_OK; - } else - { - debug_printf("!! Wrong checksum..."); - } - } else - { - debug_printf("!! Wrong response received!"); - break; - } - } - else if (result == 0) - debug_printf("Connection closed\n"); - else + // 64 bytes received? + if (result == 64) { + if (device->response[0] == 0xAA && + device->response[6] == device->requestID) { + if (device->response[7] == getChecksum(device->response)) { + debug_printf(" Received!"); + return PK_OK; + } else { + debug_printf("!! Wrong checksum..."); + } + } else { + debug_printf("!! Wrong response received!"); + break; + } + } else if (result == 0) + debug_printf("Connection closed\n"); + else #ifdef WIN32 - debug_printf("recv failed: %d\n", WSAGetLastError()); + debug_printf("recv failed: %d\n", WSAGetLastError()); #else - debug_printf("recv failed\n"); + debug_printf("recv failed\n"); #endif - - if (++retries1 > device->readRetries) break; - } - - if (retries2++ > device->sendRetries) break; + if (++retries1 > device->readRetries) + break; } - debug_printf("Error - timeout..."); - return PK_ERR_TRANSFER; + if (retries2++ > device->sendRetries) + break; + } + debug_printf("Error - timeout..."); + return PK_ERR_TRANSFER; } - -void PK_SetEthernetRetryCountAndTimeout(sPoKeysDevice * device, uint32_t sendRetries, uint32_t readRetries, uint32_t timeout) -{ - device->sendRetries = sendRetries; - device->readRetries = readRetries; - device->socketTimeout = timeout; +void PK_SetEthernetRetryCountAndTimeout(sPoKeysDevice *device, + uint32_t sendRetries, + uint32_t readRetries, + uint32_t timeout) { + device->sendRetries = sendRetries; + device->readRetries = readRetries; + device->socketTimeout = timeout; } - diff --git a/src/app/simhub.cpp b/src/app/simhub.cpp index 6d150b7..9c0dd79 100644 --- a/src/app/simhub.cpp +++ b/src/app/simhub.cpp @@ -192,7 +192,7 @@ void SimHubEventController::startSustainThread(void) std::chrono::milliseconds now = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); - for (std::pair entry: _sustainValues) { + for (std::pair entry : _sustainValues) { std::chrono::milliseconds sustain = entry.second.first; std::chrono::milliseconds ts = entry.second.second->timestamp(); diff --git a/src/app/simhub.h b/src/app/simhub.h index 92ef9e9..09c7033 100644 --- a/src/app/simhub.h +++ b/src/app/simhub.h @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -18,6 +19,7 @@ #if defined(_AWS_SDK) #include "aws/aws.h" +#include "common/support/threadmanager.h" #endif class ConfigManager; // forward reference @@ -32,8 +34,8 @@ class ConfigManager; // forward reference * void * to 'this' that was passed to the plugin when it registered * the callback stub, to call into the proper 'eventCallback' member */ - - typedef std::pair> SustainMapEntry; + +typedef std::pair> SustainMapEntry; class SimHubEventController { @@ -48,8 +50,10 @@ class SimHubEventController simplug_vtable loadPlugin(std::string dylibName, libconfig::Config *pluginConfigs, EnqueueEventHandler eventCallback); void terminate(void); void shutdownPlugin(simplug_vtable &pluginMethods); +#if defined(_AWS_SDK) void startSustainThread(void); void ceaseSustainThread(void); +#endif ConcurrentQueue> _eventQueue; simplug_vtable _prepare3dMethods; @@ -88,7 +92,7 @@ class SimHubEventController assert(prepare3dConfig != NULL); _prepare3dDeviceConfig = prepare3dConfig; }; - + void setPokeyConfig(libconfig::Config *pokeyConfig) { assert(pokeyConfig != NULL); diff --git a/src/common/configmanager/configmanager.h b/src/common/configmanager/configmanager.h index b12313b..d66850d 100644 --- a/src/common/configmanager/configmanager.h +++ b/src/common/configmanager/configmanager.h @@ -19,8 +19,10 @@ #include "aws/aws.h" #endif +#include "common/support/threadmanager.h" #include "log/clog.h" #include "mappingConfigManager/mappingConfigManager.h" + #include "simhub.h" #ifndef RETURN_OK diff --git a/src/common/configmanager/mappingConfigManager/mappingConfigManager.cpp b/src/common/configmanager/mappingConfigManager/mappingConfigManager.cpp index b8292ab..55c498a 100644 --- a/src/common/configmanager/mappingConfigManager/mappingConfigManager.cpp +++ b/src/common/configmanager/mappingConfigManager/mappingConfigManager.cpp @@ -91,7 +91,7 @@ int MappingConfigManager::init(void) } else { _mapping[source] = std::make_pair(source, target); - logger.log(LOG_INFO, " - adding %s", target.c_str()); + // logger.log(LOG_INFO, " - adding %s", target.c_str()); } if (sustain > 0 && !mapContains(_sustainMap, source)) { diff --git a/src/libs/plugins/common/simhubdeviceplugin.h b/src/libs/plugins/common/simhubdeviceplugin.h index a0d2bfe..c24a638 100644 --- a/src/libs/plugins/common/simhubdeviceplugin.h +++ b/src/libs/plugins/common/simhubdeviceplugin.h @@ -31,6 +31,7 @@ typedef union { int bool_value; operator bool() const { return bool_value; } operator int() const { return int_value; } + operator float() const { return float_value; } } VariantUnion; typedef struct { diff --git a/src/libs/plugins/pokey/main.cpp b/src/libs/plugins/pokey/main.cpp index 529d70f..40fe3ce 100644 --- a/src/libs/plugins/pokey/main.cpp +++ b/src/libs/plugins/pokey/main.cpp @@ -104,6 +104,9 @@ int PokeyDevicePluginStateManager::deliverValue(GenericTLV *data) else if (data->type == ConfigType::CONFIG_INT) { retVal = device->targetValue(data->name, (int)data->value); } + else if (data->type == ConfigType::CONFIG_FLOAT) { + device->targetValue(data->name, (float)data->value); + } } else { std::cout << "NO DEVICE!" << std::endl; @@ -224,6 +227,59 @@ bool PokeyDevicePluginStateManager::deviceConfiguration(libconfig::SettingIterat return retVal; } +bool PokeyDevicePluginStateManager::devicePWMConfiguration(libconfig::Setting *pwm, std::shared_ptr pokeyDevice) +{ + bool retVal = true; + + int PWMLength = pwm->getLength(); + + if (PWMLength > 0) { + _logger(LOG_INFO, " [%s] - Found %i PWM Channels", pokeyDevice->name().c_str(), PWMLength); + + for (libconfig::SettingIterator iter = pwm->begin(); iter != pwm->end(); iter++) { + int channel = 0; + std::string name = ""; + std::string description = ""; + std::string units = ""; + uint32_t leftDutyCycle = 0; + uint32_t rightDutyCycle = 0; + uint32_t period = 250000; // pokey clock cycles + + try { + iter->lookupValue("channel", channel); + iter->lookupValue("name", name); + iter->lookupValue("description", description); + iter->lookupValue("units", units); + iter->lookupValue("leftDutyCycle", leftDutyCycle); + iter->lookupValue("rightDutyCycle", rightDutyCycle); + iter->lookupValue("period", period); + } + catch (const libconfig::SettingNotFoundException &nfex) { + _logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath()); + } + + if (addTargetToDeviceTargetList(name, pokeyDevice)) { + pokeyDevice->addPWM(channel, name, description, units, leftDutyCycle, rightDutyCycle, period); + _logger(LOG_INFO, " - Added PWM channel %i - %s", channel, name.c_str()); + + /* + // -- uncomment to test + + pokeyDevice->targetValue(name, 0.0f); + + for (float idx = 0.0f; idx <= 1.00f; idx += 0.05f) { + pokeyDevice->targetValue(name, idx); + } + + pokeyDevice->targetValue(name, 0.0f); + */ + } + } + } + + return retVal; +} + void PokeyDevicePluginStateManager::loadTransform(std::string pinName, libconfig::Setting *transform) { _logger(LOG_INFO, " - transform %s", pinName.c_str()); @@ -390,22 +446,6 @@ std::pair, std::string> PokeyDevicePluginStateManag return retVal; } -bool PokeyDevicePluginStateManager::devicePWMConfiguration(libconfig::Setting *pwm, std::shared_ptr pokeyDevice) -{ - bool retVal = true; - int pwmCount = pwm->getLength(); - - if (pwmCount > 0) { - _logger(LOG_INFO, " [%s] - Found %i PWM Channels", pokeyDevice->name().c_str(), pwmCount); - int encoderIndex = 0; - - for (libconfig::SettingIterator iter = pwm->begin(); iter != pwm->end(); iter++) { - } - } - - return retVal; -} - bool PokeyDevicePluginStateManager::deviceEncodersConfiguration(libconfig::Setting *encoders, std::shared_ptr pokeyDevice) { /** @@ -594,7 +634,7 @@ int PokeyDevicePluginStateManager::preflightComplete(void) deviceDisplaysConfiguration(&iter->lookup("displays"), pokeyDevice); if (iter->exists("pwm")) - devicePWMConfiguration(&iter->lookup("displays"), pokeyDevice); + devicePWMConfiguration(&iter->lookup("pwm"), pokeyDevice); pokeyDevice->startPolling(); } diff --git a/src/libs/plugins/pokey/pokeyDevice.cpp b/src/libs/plugins/pokey/pokeyDevice.cpp index 6f9c614..0e1c21a 100644 --- a/src/libs/plugins/pokey/pokeyDevice.cpp +++ b/src/libs/plugins/pokey/pokeyDevice.cpp @@ -1,4 +1,6 @@ +#include #include +#include #include "elements/attributes/attribute.h" #include "main.h" @@ -295,6 +297,8 @@ void PokeyDevice::addPin(int pinIndex, std::string pinName, int pinNumber, std:: mapNameToPin(pinName.c_str(), pinNumber); + int portNumber = pinNumber - 1; + _pins[pinIndex].pinName = pinName; _pins[pinIndex].pinIndex = pinIndex; _pins[pinIndex].type = pinType.c_str(); @@ -304,6 +308,32 @@ void PokeyDevice::addPin(int pinIndex, std::string pinName, int pinNumber, std:: _pins[pinIndex].description = description; } +void PokeyDevice::addPWM( + uint8_t channel, + std::string name, + std::string description, + std::string units, + uint32_t leftDutyCycle, + uint32_t rightDutyCycle, + uint32_t period) +{ + _pwmChannels[channel] = true; + + mapNameToPWM(name.c_str(), channel); + + _pwm[channel].name = name; + _pwm[channel].description = description; + _pwm[channel].units = units; + _pwm[channel].leftDutyCycle = leftDutyCycle; + _pwm[channel].rightDutyCycle = rightDutyCycle; + _pwm[channel].period = period; + + PK_PWMConfigurationGet(_pokey); + _pokey->PWM.PWMperiod = _pwm[channel].period; + _pokey->PWM.PWMenabledChannels[channel] = true; + int ret = PK_PWMConfigurationSet(_pokey); +} + void PokeyDevice::startPolling() { uv_run(uv_default_loop(), UV_RUN_DEFAULT); @@ -351,6 +381,7 @@ std::string PokeyDevice::hardwareTypeString() if (_hardwareType == 31) { return "Pokey 57E"; } + return "Unknown"; } @@ -391,7 +422,6 @@ bool PokeyDevice::validateEncoder(int encoderNumber) bool PokeyDevice::isEncoderCapable(int pin) { - switch (pin) { case 1: return (bool)PK_CheckPinCapability(_pokey, 0, PK_AllPinCap_fastEncoder1A); @@ -413,7 +443,15 @@ bool PokeyDevice::isEncoderCapable(int pin) } void PokeyDevice::addEncoder( - int encoderNumber, uint32_t defaultValue, std::string name, std::string description, int min, int max, int step, int invertDirection, std::string units) + int encoderNumber, + uint32_t defaultValue, + std::string name, + std::string description, + int min, + int max, + int step, + int invertDirection, + std::string units) { assert(encoderNumber >= 1); @@ -520,6 +558,24 @@ uint32_t PokeyDevice::targetValue(std::string targetName, int value) return 0; } +using namespace std::chrono_literals; + +uint32_t PokeyDevice::targetValue(std::string targetName, float value) +{ + uint8_t channel = PWMFromName(targetName); + + // value is percent, so calculate cycles back from left cycle count + + uint32_t duty = _pwm[channel].leftDutyCycle - ((_pwm[channel].leftDutyCycle - _pwm[channel].rightDutyCycle) * value); + PK_SL_PWM_SetDuty(_pokey, channel, duty); + PK_PWMUpdate(_pokey); + std::this_thread::sleep_for(250ms); + PK_SL_PWM_SetDuty(_pokey, channel, 0); + PK_PWMUpdate(_pokey); + + return 0; +} + uint32_t PokeyDevice::targetValue(std::string targetName, bool value) { uint32_t retValue = -1; @@ -570,7 +626,6 @@ uint8_t PokeyDevice::displayNumber(uint8_t displayNumber, std::string targetName } if (numberOfChars <= groupLength) { - for (int i = 0; i < numberOfChars; i++) { int displayOffset = (int)charString.at(i) - 48; int convertedValue = _intToDisplayRow[displayOffset]; @@ -659,11 +714,27 @@ int PokeyDevice::pinFromName(std::string targetName) return -1; } +uint8_t PokeyDevice::PWMFromName(std::string targetName) +{ + std::map::iterator it = _pwmMap.find(targetName); + + if (it != _pwmMap.end()) { + return it->second; + } + else + return -1; +} + void PokeyDevice::mapNameToPin(std::string name, int pin) { _pinMap.emplace(name, pin); } +void PokeyDevice::mapNameToPWM(std::string name, int pin) +{ + _pwmMap.emplace(name, pin); +} + void PokeyDevice::mapNameToEncoder(std::string name, int encoderNumber) { _encoderMap.emplace(name, encoderNumber); diff --git a/src/libs/plugins/pokey/pokeyDevice.h b/src/libs/plugins/pokey/pokeyDevice.h index 04125db..3fc6593 100644 --- a/src/libs/plugins/pokey/pokeyDevice.h +++ b/src/libs/plugins/pokey/pokeyDevice.h @@ -4,9 +4,11 @@ #include "PoKeysLib.h" #include "common/simhubdeviceplugin.h" #include +#include #include #include #include +#include #include #include #include @@ -30,6 +32,10 @@ #define MAX_DIGITS 10 #define MAX_PWM_CHANNELS 6 +#define PWM_SERVO_LEFT 50000 +#define PWM_SERVO_RIGHT 25000 +#define PWM_SERVO_CENTER 37500 + typedef struct { std::string pinName; int pinNumber; @@ -73,10 +79,13 @@ typedef struct { typedef struct { uint8_t id; + std::string units; std::string name; std::string description; + uint8_t pin; + uint32_t leftDutyCycle; + uint32_t rightDutyCycle; uint32_t period; - uint32_t duty; } device_pwm_t; class PokeyDevicePluginStateManager; @@ -108,10 +117,13 @@ class PokeyDevice sPoKeysDevice *_pokey; void *_callbackArg; SPHANDLE _pluginInstance; + device_port_t _pins[MAX_PINS]; device_pwm_t _pwm[MAX_PWM_CHANNELS]; device_encoder_t _encoders[MAX_ENCODERS]; device_matrixLED_t _matrixLED[MAX_MATRIX_LEDS]; + uint8_t _pwmChannels[6]; + uint8_t _intToDisplayRow[MAX_DIGITS]; EnqueueEventHandler _enqueueCallback; @@ -121,6 +133,7 @@ class PokeyDevice int pinFromName(std::string targetName); int pinIndexFromName(std::string targetName); + uint8_t PWMFromName(std::string targetName); uint8_t displayFromName(std::string targetName); uint8_t displayNumber(uint8_t displayNumwber, std::string targetName, int value); @@ -133,12 +146,15 @@ class PokeyDevice bool ownsPin(std::string pinName); bool validatePinCapability(int, std::string); bool validateEncoder(int encoderNumber); + void mapNameToPin(std::string name, int pin); void mapNameToEncoder(std::string name, int encoderNumber); void mapNameToMatrixLED(std::string name, int id); + void mapNameToPWM(std::string name, int pin); uint32_t targetValue(std::string targetName, bool value); uint32_t targetValue(std::string targetName, int value); + uint32_t targetValue(std::string targetName, float value); uint32_t inputPin(uint8_t pin, bool invert = false); uint32_t outputPin(uint8_t pin); int32_t name(std::string name); @@ -174,9 +190,34 @@ class PokeyDevice bool isPinDigitalOutput(uint8_t pin); bool isPinDigitalInput(uint8_t pin); bool isEncoderCapable(int pin); - void addPin(int pindex, std::string name, int pinNumber, std::string pinType, int defaultValue, std::string description, bool invert); - void addEncoder(int encoderNumber, uint32_t defaultValue, std::string name = DEFAULT_ENCODER_NAME, std::string description = DEFAULT_ENCODER_DESCRIPTION, - int min = DEFAULT_ENCODER_MIN, int max = DEFAULT_ENCODER_MAX, int step = DEFAULT_ENCODER_STEP, int invertDirection = DEFAULT_ENCODER_DIRECTION, std::string units = ""); + + void addPin(int pinIndex, + std::string name, + int pinNumber, + std::string pinType, + int defaultValue = 0, + std::string description = "None", + bool invert = false); + + void addPWM( + uint8_t pinNumber, + std::string name, + std::string description, + std::string units, + uint32_t leftDutyCycle, + uint32_t rightDutyCycle, + uint32_t period); + + void addEncoder( + int encoderNumber, + uint32_t defaultValue, + std::string name = DEFAULT_ENCODER_NAME, + std::string description = DEFAULT_ENCODER_DESCRIPTION, + int min = DEFAULT_ENCODER_MIN, + int max = DEFAULT_ENCODER_MAX, + int step = DEFAULT_ENCODER_STEP, + int invertDirection = DEFAULT_ENCODER_DIRECTION, + std::string units = ""); void addMatrixLED(int id, std::string name, std::string type); void configMatrixLED(int id, int rows, int cols = 8, int enabled = 0); diff --git a/tools/aws/cfn/create.sh b/tools/aws/cfn/create.sh index 16335b3..8717275 100755 --- a/tools/aws/cfn/create.sh +++ b/tools/aws/cfn/create.sh @@ -2,7 +2,10 @@ echo "Creating simhub environment" -cd stacks/kinesis +cd stacks/dynamo +./create.sh + +cd ../kinesis ./create.sh cd ../lambda diff --git a/tools/aws/cfn/stacks/dynamo/config b/tools/aws/cfn/stacks/dynamo/config new file mode 100644 index 0000000..3931300 --- /dev/null +++ b/tools/aws/cfn/stacks/dynamo/config @@ -0,0 +1,3 @@ +STACK_NAME=simhubDynamo +S3_BUCKET=s3://teichtah-lambda-functions +REGION=us-east-1 \ No newline at end of file diff --git a/tools/aws/cfn/stacks/dynamo/create.sh b/tools/aws/cfn/stacks/dynamo/create.sh new file mode 100755 index 0000000..46099c9 --- /dev/null +++ b/tools/aws/cfn/stacks/dynamo/create.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +. config + + +echo "Creating Dynamo Table(s)" +/Users/teichtah/Library/Python/2.7/bin/aws cloudformation create-stack --stack-name $STACK_NAME --template-body file://stack.json --region $REGION + +if [ $? -eq 0 ] +then + echo " - waiting for Dynamo creation to complete" + /Users/teichtah/Library/Python/2.7/bin/aws cloudformation wait stack-create-complete --stack-name $STACK_NAME --region $REGION + echo "Dynamo creation completed." + /Users/teichtah/Library/Python/2.7/bin/aws cloudformation describe-stacks --stack-name $STACK_NAME --region $REGION --output json | jq '.[][0].Outputs' + +else + echo "Dynam creation failed" +fi diff --git a/tools/aws/cfn/stacks/dynamo/delete.sh b/tools/aws/cfn/stacks/dynamo/delete.sh new file mode 100755 index 0000000..c20e92d --- /dev/null +++ b/tools/aws/cfn/stacks/dynamo/delete.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +. config + +echo "Deleting cloudformation stack "$STACK_NAME +/Users/teichtah/Library/Python/2.7/bin/aws cloudformation delete-stack --stack-name $STACK_NAME --region $REGION + +if [ $? -eq 0 ] +then + echo " - waiting for deletion to complete" + /Users/teichtah/Library/Python/2.7/bin/aws cloudformation wait stack-delete-complete --stack-name $STACK_NAME --region $REGION +fi diff --git a/tools/aws/cfn/stacks/dynamo/stack.json b/tools/aws/cfn/stacks/dynamo/stack.json new file mode 100644 index 0000000..56a8adf --- /dev/null +++ b/tools/aws/cfn/stacks/dynamo/stack.json @@ -0,0 +1,58 @@ +{ + "AWSTemplateFormatVersion": "2010-09-09", + "Parameters": { + "EnvironmentName": { + "Description": "The string that will be prefixed to each instance name", + "Type": "String", + "MinLength": "3", + "MaxLength": "16", + "Default": "simhub", + "AllowedPattern": "[a-zA-Z0-9]*", + "ConstraintDescription": "Environment names must be 3-16 characters and contain only a-z and 0-9." + }, + "DynamoTableName": { + "Description": "DynamoDB", + "Type": "String", + "MinLength": "3", + "MaxLength": "16", + "Default": "simhub-KeyVal", + "AllowedPattern": "[a-zA-Z0-9-]*", + "ConstraintDescription": "dynamo db names must be 3-16 characters and contain only a-z and 0-9." + } + }, + "Resources": { + "DynamoTable": { + "Type": "AWS::DynamoDB::Table", + "Properties": { + "AttributeDefinitions": [{ + "AttributeName": "source", + "AttributeType": "S" + }], + "KeySchema": [{ + "AttributeName": "source", + "KeyType": "HASH" + }], + "ProvisionedThroughput": { + "ReadCapacityUnits": "10", + "WriteCapacityUnits": "10" + }, + "TableName": { + "Ref": "DynamoTableName" + } + } + } + }, + "Outputs": { + "DynamoARN": { + "Value": { + "Fn::GetAtt": ["DynamoTable", "Arn"] + }, + "Description": "DynamoTable ARN", + "Export": { + "Name": { + "Fn::Sub": "${AWS::StackName}-DynamoTable-ARN" + } + } + } + } +} \ No newline at end of file diff --git a/tools/aws/cfn/stacks/dynamo/update.sh b/tools/aws/cfn/stacks/dynamo/update.sh new file mode 100755 index 0000000..8fc56c4 --- /dev/null +++ b/tools/aws/cfn/stacks/dynamo/update.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +. config + +echo "Updating Dynamo" + +aws cloudformation update-stack --stack-name $STACK_NAME --template-body file://stack.json --region $REGION +echo " - waiting for dynamo update to complete. This may take some time" +aws cloudformation wait stack-update-complete --stack-name $STACK_NAME --region $REGION diff --git a/tools/aws/cfn/stacks/kinesis/create.sh b/tools/aws/cfn/stacks/kinesis/create.sh index 1e34783..351efb0 100755 --- a/tools/aws/cfn/stacks/kinesis/create.sh +++ b/tools/aws/cfn/stacks/kinesis/create.sh @@ -4,15 +4,15 @@ echo "Creating Kinesis Stream" -aws cloudformation create-stack --stack-name $STACK_NAME --template-body file://stack.json +aws cloudformation create-stack --stack-name $STACK_NAME --template-body file://stack.json --region $REGION if [ $? -eq 0 ] then echo " - waiting for Kinesis Stream creation to complete" - aws cloudformation wait stack-create-complete --stack-name $STACK_NAME + aws cloudformation wait stack-create-complete --stack-name $STACK_NAME --region $REGION aws s3 rm $S3_BUCKET/$S3_KEY echo "Kinesis Stream creation completed." - aws cloudformation describe-stacks --stack-name $STACK_NAME --output json | jq '.[][0].Outputs' + aws cloudformation describe-stacks --stack-name $STACK_NAME --region $REGION --output json | jq '.[][0].Outputs' else echo "Kinesis Stream creation failed" diff --git a/tools/aws/cfn/stacks/kinesis/stack.json b/tools/aws/cfn/stacks/kinesis/stack.json index f6841f1..54f13b0 100644 --- a/tools/aws/cfn/stacks/kinesis/stack.json +++ b/tools/aws/cfn/stacks/kinesis/stack.json @@ -18,6 +18,15 @@ "Default": "simhubStream", "AllowedPattern": "[a-zA-Z0-9]*", "ConstraintDescription": "Environment names must be 3-16 characters and contain only a-z and 0-9." + }, + "DynamoTable": { + "Description": "DynamoDB", + "Type": "String", + "MinLength": "3", + "MaxLength": "16", + "Default": "simhub", + "AllowedPattern": "[a-zA-Z0-9]*", + "ConstraintDescription": "dynamo db names must be 3-16 characters and contain only a-z and 0-9." } }, "Resources": { @@ -35,7 +44,10 @@ "Outputs": { "KinesisStreamARN": { "Value": { - "Fn::GetAtt": ["KinesisStream", "Arn"] + "Fn::GetAtt": [ + "KinesisStream", + "Arn" + ] }, "Description": "Kinesis Stream", "Export": { diff --git a/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js b/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js index 81b4d25..cd845be 100644 --- a/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js +++ b/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js @@ -5,8 +5,10 @@ var AWS = require('aws-sdk'); var s3 = new AWS.S3(); var cloudwatch = new AWS.CloudWatch(); -var dynamodb = new AWS.DynamoDB(); - +var dynamodb = new AWS.DynamoDB({ + region: process.env.dynamoRegion +}); +var dynamoTable = process.env.dynamoTable /** * cleanJSONString * @@ -16,34 +18,43 @@ var dynamodb = new AWS.DynamoDB(); function cleanJSONString(string) { // preserve newlines, etc - use valid JSON string = string.replace(/\\n/g, '\\n') - .replace(/\\'/g, '\\\'') - .replace(/\\"/g, '\\"') - .replace(/\\&/g, '\\&') - .replace(/\\r/g, '\\r') - .replace(/\\t/g, '\\t') - .replace(/\\b/g, '\\b') - .replace(/\\f/g, '\\f'); + .replace(/\\'/g, '\\\'') + .replace(/\\"/g, '\\"') + .replace(/\\&/g, '\\&') + .replace(/\\r/g, '\\r') + .replace(/\\t/g, '\\t') + .replace(/\\b/g, '\\b') + .replace(/\\f/g, '\\f'); // remove non-printable and other non-valid JSON chars return string.replace(/[\u0000-\u0019]+/g, ''); } function writeToDynamo(name, value, units, description) { + var params = { Item: { - 'source': {S: name}, - 'value': {S: value}, - 'units': {S: units}, - 'description': {S: description} + 'source': { + S: name + }, + 'value': { + S: value + }, + 'units': { + S: units + }, + 'title': { + S: description + } }, ReturnConsumedCapacity: 'TOTAL', - TableName: 'simhub' + TableName: dynamoTable }; - dynamodb.putItem(params, function(err, data) { + dynamodb.putItem(params, function (err, data) { if (err) - console.log(err, err.stack, params); // an error occurred + console.log(err, err.stack, params); // an error occurred else - console.log(data); // successful response + console.log(data); // successful response }); } @@ -53,9 +64,10 @@ function putCloudwatchMetric(metricName, dimName, dimValue, ts, value) { /* required */ { MetricName: metricName, - Dimensions: [ - {Name: dimName, Value: dimValue}, - ], + Dimensions: [{ + Name: dimName, + Value: dimValue + }, ], StorageResolution: 1, Timestamp: new Date(ts).toISOString(), Unit: 'None', @@ -66,18 +78,18 @@ function putCloudwatchMetric(metricName, dimName, dimValue, ts, value) { Namespace: 'simhub' /* required */ }; - cloudwatch.putMetricData(params, function(err, data) { + cloudwatch.putMetricData(params, function (err, data) { if (err) - console.log(err, err.stack); // an error occurred + console.log(err, err.stack); // an error occurred else - console.log(data); // successful response + console.log(data); // successful response }); } /** * Main lambda handler and entry point */ -exports.index = function(event, context, callback) { +exports.index = function (event, context, callback) { // find the number of records being given to us by kinesis var recordCount = event.Records.length; @@ -98,4 +110,4 @@ exports.index = function(event, context, callback) { callback(null, 'Complete'); -} +} \ No newline at end of file diff --git a/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json b/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json index c40c5d5..adab728 100644 --- a/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json +++ b/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json @@ -19,14 +19,23 @@ "Type": "String", "Default": "teichtah-lambda-functions", "Description": "Lambda function bucket" + }, + "DynamoRegion": { + "Type": "String", + "Default": "us-east-1", + "Description": "AWS region of the dynamoDB table" + }, + "DynamoTable": { + "Type": "String", + "Default": "simhub-KeyVal", + "Description": "Name of the dynamoDB table" } }, "Resources": { "ProcessKinesisFunction": { "Type": "AWS::Lambda::Function", "Properties": { - "Tags": [ - { + "Tags": [{ "Key": "Environment", "Value": { "Ref": "EnvironmentName" @@ -49,7 +58,16 @@ "Ref": "ProcessKinesisFunctionKey" } }, - "Environment": {}, + "Environment": { + "Variables": { + "dynamoRegion": { + "Ref": "DynamoRegion" + }, + "dynamoTable": { + "Ref": "DynamoTable" + } + } + }, "Runtime": "nodejs6.10", "Timeout": "120", "MemorySize": "1024", @@ -72,9 +90,9 @@ "Arn" ] }, - "StartingPosition": "TRIM_HORIZON" - }, - "BatchSize": 10 + "StartingPosition": "LATEST", + "BatchSize": 5 + } }, "LambdaPermission": { "Type": "AWS::Lambda::Permission", @@ -89,8 +107,7 @@ "Principal": "apigateway.amazonaws.com", "SourceArn": { "Fn::Join": [ - "", - [ + "", [ "arn:aws:execute-api:", { "Ref": "AWS::Region"