From dfacba6952bf365d87c3f540f99d29066282c4a3 Mon Sep 17 00:00:00 2001 From: Joonas Koivunen Date: Sat, 9 Nov 2019 20:42:47 +0200 Subject: [PATCH 01/11] refactor include stdbool --- simplemotion_types.h | 1 + 1 file changed, 1 insertion(+) diff --git a/simplemotion_types.h b/simplemotion_types.h index be38d76..cd539ae 100644 --- a/simplemotion_types.h +++ b/simplemotion_types.h @@ -5,6 +5,7 @@ #define SIMPLEMOTION_TYPES_H #include +#include //possible return values (SM_STATUS type) #define SM_NONE 0 From 4dcd7115114a16f6d65c3c0d61613d26dc49e874 Mon Sep 17 00:00:00 2001 From: Joonas Koivunen Date: Sat, 9 Nov 2019 20:47:01 +0200 Subject: [PATCH 02/11] refactor replace smbool/smtrue/smfalse with std ones --- bufferedmotion.c | 26 +++---- bufferedmotion.h | 6 +- busdevice.c | 66 ++++++++-------- busdevice.h | 16 ++-- devicedeployment.c | 174 +++++++++++++++++++++---------------------- devicedeployment.h | 4 +- simplemotion.c | 170 +++++++++++++++++++++--------------------- simplemotion.h | 8 +- simplemotion_types.h | 18 +++-- 9 files changed, 245 insertions(+), 243 deletions(-) diff --git a/bufferedmotion.c b/bufferedmotion.c index 8b1b389..219e81f 100644 --- a/bufferedmotion.c +++ b/bufferedmotion.c @@ -11,18 +11,18 @@ SM_STATUS smBufferedInit(BufferedMotionAxis *newAxis, smbus handle, smaddr devic if(sampleRate<1 || sampleRate>2500) return recordStatus(handle,SM_ERR_PARAMETER); - newAxis->initialized=smfalse; + newAxis->initialized=false; newAxis->bushandle=handle; newAxis->samplerate=sampleRate; newAxis->deviceAddress=deviceAddress; newAxis->readParamAddr=readParamAddr; newAxis->readParamLength=readDataLength; - newAxis->readParamInitialized=smfalse; + newAxis->readParamInitialized=false; newAxis->numberOfDiscardableReturnDataPackets=0; newAxis->driveClock=0; newAxis->bufferFill=0; newAxis->numberOfPendingReadPackets=0; - newAxis->driveFlagsModifiedAtInit=smfalse; + newAxis->driveFlagsModifiedAtInit=false; newAxis->deviceCapabilityFlags1=0; newAxis->deviceCapabilityFlags2=0; @@ -52,7 +52,7 @@ SM_STATUS smBufferedInit(BufferedMotionAxis *newAxis, smbus handle, smaddr devic if(sampleRate<2500) { smSetParameter(handle,deviceAddress,SMP_DRIVE_FLAGS,newAxis->driveFlagsBeforeInit|FLAG_USE_INPUT_LP_FILTER); - newAxis->driveFlagsModifiedAtInit=smtrue; + newAxis->driveFlagsModifiedAtInit=true; } } @@ -68,7 +68,7 @@ SM_STATUS smBufferedInit(BufferedMotionAxis *newAxis, smbus handle, smaddr devic //FIXME can cause unnecessary initialized=false status if there was error flags in cumulative status before calling this func if(getCumulativeStatus(handle)==SM_OK) - newAxis->initialized=smtrue; + newAxis->initialized=true; return getCumulativeStatus(handle); } @@ -79,15 +79,15 @@ SM_STATUS smBufferedDeinit( BufferedMotionAxis *axis ) smBufferedAbort(axis); //restore drive in pre-init state - if(axis->initialized==smtrue) + if(axis->initialized==true) { smSetParameter(axis->bushandle,axis->deviceAddress,SMP_TRAJ_PLANNER_ACCEL,axis->driveAccelerationBeforeInit); - if(axis->driveFlagsModifiedAtInit==smtrue)//if flags parameter modified, then restore the origianl value + if(axis->driveFlagsModifiedAtInit==true)//if flags parameter modified, then restore the origianl value smSetParameter(axis->bushandle,axis->deviceAddress,SMP_DRIVE_FLAGS,axis->driveFlagsBeforeInit); } - axis->initialized=smfalse; - axis->readParamInitialized=smfalse; + axis->initialized=false; + axis->readParamInitialized=false; return getCumulativeStatus(axis->bushandle); } @@ -124,7 +124,7 @@ smint32 smBufferedGetMaxFillSize(BufferedMotionAxis *axis, smint32 numBytesFree numBytesFree=SM485_MAX_PAYLOAD_BYTES; //calculate number of points that can be uploaded to buffer (max size SM485_MAX_PAYLOAD_BYTES bytes and fill consumption is 2+4+2+3*(n-1) bytes) - if(axis->readParamInitialized==smtrue) + if(axis->readParamInitialized==true) //*numPoints=(freebytes-2-4-2)/3+1; return numBytesFree/4; else @@ -135,7 +135,7 @@ smint32 smBufferedGetMaxFillSize(BufferedMotionAxis *axis, smint32 numBytesFree smint32 smBufferedGetBytesConsumed(BufferedMotionAxis *axis, smint32 numFillPoints ) { //calculate number of bytes that the number of fill points will consume from buffer - if(axis->readParamInitialized==smtrue) + if(axis->readParamInitialized==true) return numFillPoints*4; else return numFillPoints*4 +2+3+2+3+2;//if read data uninitialized, it takes extra n bytes to init on next fill, so reduce it here @@ -154,7 +154,7 @@ SM_STATUS smBufferedFillAndReceive(BufferedMotionAxis *axis, smint32 numFillPoin // cmdBufferSizeBytes=freeBytesInDeviceBuffer;//get empty buffer size //first initialize the stream if not done yet - if(axis->readParamInitialized==smfalse) + if(axis->readParamInitialized==false) { //set acceleration to "infinite" to avoid modification of user supplied trajectory inside drive smAppendSMCommandToQueue(axis->bushandle,SMPCMD_SETPARAMADDR,SMP_RETURN_PARAM_ADDR); @@ -166,7 +166,7 @@ SM_STATUS smBufferedFillAndReceive(BufferedMotionAxis *axis, smint32 numFillPoin //next time we read return data, we discard first 4 return packets to avoid unexpected read data to user axis->numberOfDiscardableReturnDataPackets+=5; - axis->readParamInitialized=smtrue; + axis->readParamInitialized=true; } if(numFillPoints>=1)//send first fill data diff --git a/bufferedmotion.h b/bufferedmotion.h index b7da4b6..dd0e32b 100644 --- a/bufferedmotion.h +++ b/bufferedmotion.h @@ -10,8 +10,8 @@ extern "C"{ //typedef enum _smBufferedState {BufferedStop=0,BufferedRun=1} smBufferedState; typedef struct _BufferedMotionAxis { - smbool initialized; - smbool readParamInitialized; + bool initialized; + bool readParamInitialized; smint32 numberOfDiscardableReturnDataPackets; smint32 numberOfPendingReadPackets;//number of read data packets that should be arriving from device (to read rest of pending data, use smBufferedFillAndReceive(numFillPoints=0) until this variable this goes to zero) smbus bushandle; @@ -20,7 +20,7 @@ typedef struct _BufferedMotionAxis { smint16 readParamAddr; smuint8 readParamLength; smint32 driveFlagsBeforeInit; - smbool driveFlagsModifiedAtInit;//true if deInit should restore driveFlagsBeforeInit + bool driveFlagsModifiedAtInit;//true if deInit should restore driveFlagsBeforeInit smint32 driveAccelerationBeforeInit; smuint16 driveClock;//clock counter is updated at smBufferedRunAndSyncClocks only for the one axis that is used with that func. clock is running up at 10kHz count rate, meaning that it rolls over every 6.5536 secs smint32 bufferLength;//buffer lenght in bytes of the device. note this may be different in different devices types. so call smBufferedGetFree on the device that has the smallest buffer. however as of 2.2016 all GD drives have 2048 bytes buffers. diff --git a/busdevice.c b/busdevice.c index da7afcd..bfca58c 100644 --- a/busdevice.c +++ b/busdevice.c @@ -18,7 +18,7 @@ unsigned long SMBusBaudrate=SM_BAUDRATE; //the next opened port (with smOpenBus) typedef struct _SMBusDevice { //common - smbool opened; + bool opened; SM_STATUS cumulativeSmStatus; @@ -36,7 +36,7 @@ typedef struct _SMBusDevice } SMBusDevice; //init on first open -smbool bdInitialized=smfalse; +bool bdInitialized=false; SMBusDevice BusDevice[SM_MAX_BUSES]; //init device struct table @@ -45,10 +45,10 @@ void smBDinit() int i; for(i=0;i=SM_MAX_BUSES) return smfalse; + if(handle<0) return false; + if(handle>=SM_MAX_BUSES) return false; return BusDevice[handle].opened; } //return true if ok -smbool smBDClose( const smbusdevicehandle handle ) +bool smBDClose( const smbusdevicehandle handle ) { //check if handle valid & open - if( smIsBDHandleOpen(handle)==smfalse ) return smfalse; + if( smIsBDHandleOpen(handle)==false ) return false; BusDevice[handle].busCloseCallback(BusDevice[handle].busDevicePointer ); - BusDevice[handle].opened=smfalse; - return smtrue; + BusDevice[handle].opened=false; + return true; } @@ -149,10 +149,10 @@ smbool smBDClose( const smbusdevicehandle handle ) //write one byte to buffer and send later with smBDTransmit() //returns true on success -smbool smBDWrite(const smbusdevicehandle handle, const smuint8 byte ) +bool smBDWrite(const smbusdevicehandle handle, const smuint8 byte ) { //check if handle valid & open - if( smIsBDHandleOpen(handle)==smfalse ) return smfalse; + if( smIsBDHandleOpen(handle)==false ) return false; if(BusDevice[handle].txBufferUsed=dataLen)//end of data buffer { - *eof=smtrue; + *eof=true; c=0; } else { - *eof=smfalse; + *eof=false; c=data[(*readPosition)]; (*readPosition)++; } //eol or eof - if( (*eof)==smtrue || c=='\n' || c=='\r' || len>=charlimit-1 ) + if( (*eof)==true || c=='\n' || c=='\r' || len>=charlimit-1 ) { output[len]=0;//terminate str return len; @@ -83,7 +83,7 @@ typedef struct { int address; double value; - smbool readOnly; + bool readOnly; double scale; double offset; } Parameter; @@ -110,9 +110,9 @@ int decimalNumberToDouble( const char *str, double *output ) { double out=0, decimalcoeff=1.0; int i=0; - smbool decimalPointFound=smfalse; - smbool done=smfalse; - while(done==smfalse) + bool decimalPointFound=false; + bool done=false; + while(done==false) { char c=str[i]; int number=c-'0';//char to value 0-9 @@ -127,16 +127,16 @@ int decimalNumberToDouble( const char *str, double *output ) else if(number>=0 && number <=9) //is number { out=10.0*out+number; - if(decimalPointFound==smtrue) + if(decimalPointFound==true) decimalcoeff*=0.1; } else if (c=='.')//is decimal point { - decimalPointFound=smtrue; + decimalPointFound=true; } else if(c=='\n' || c=='\r' || c==' ' || c==0 || c=='e' )//end of string { - done=smtrue; + done=true; } else//bad charachter { @@ -196,8 +196,8 @@ int stringToInt( const char *str, int *output ) int out=0; int i=0; int coeff=1; - smbool done=smfalse; - while(done==smfalse) + bool done=false; + while(done==false) { char c=str[i]; int number=c-'0';//char to value 0-9 @@ -212,7 +212,7 @@ int stringToInt( const char *str, int *output ) } else if(c=='\n' || c=='\r' || c==' ' || c==0 )//end of string { - done=smtrue; + done=true; } else//bad charachter { @@ -226,32 +226,32 @@ int stringToInt( const char *str, int *output ) return 1; } -smbool parseDRCIntKey( const smuint8 *drcData, const int drcDataLen, const char *key, int *outValue ) +bool parseDRCIntKey( const smuint8 *drcData, const int drcDataLen, const char *key, int *outValue ) { int pos=findSubstring(drcData,drcDataLen,key); if(pos<0) - return smfalse; //key not found + return false; //key not found if( stringToInt((char*)(&drcData[pos]+strlen(key)),outValue) != 1) - return smfalse; //parse failed + return false; //parse failed - return smtrue; + return true; } -//read DRC file version nr and nubmer of params it contains. if succes, returns smtrue. if invalid file, return smfalse -smbool parseDRCInfo( const smuint8 *drcData, const int drcDataLen, int *DRCVersion, int *numParams, int *DRCFileFeatureBits, int *DRCEssentialFileFeatureBits ) +//read DRC file version nr and nubmer of params it contains. if succes, returns true. if invalid file, return false +bool parseDRCInfo( const smuint8 *drcData, const int drcDataLen, int *DRCVersion, int *numParams, int *DRCFileFeatureBits, int *DRCEssentialFileFeatureBits ) { const char *DRCFileFeatureBitsKey="FileFeatureBits="; const char *DRCEssentialFileFeatureBitsKey="FileFeatureBitsEssential="; - if( parseDRCIntKey(drcData,drcDataLen,"DRCVersion=",DRCVersion) == smfalse ) return smfalse; //parse failed - if( parseDRCIntKey(drcData,drcDataLen,"size=",numParams) == smfalse ) return smfalse; //parse failed + if( parseDRCIntKey(drcData,drcDataLen,"DRCVersion=",DRCVersion) == false ) return false; //parse failed + if( parseDRCIntKey(drcData,drcDataLen,"size=",numParams) == false ) return false; //parse failed //v 111 and beyond should have file feature bits defined if(*DRCVersion>=111) { - if( parseDRCIntKey(drcData,drcDataLen,"FileFeatureBits=",DRCFileFeatureBits) == smfalse ) return smfalse; //parse failed - if( parseDRCIntKey(drcData,drcDataLen,"FileFeatureBitsEssential=",DRCEssentialFileFeatureBits) == smfalse ) return smfalse; //parse failed + if( parseDRCIntKey(drcData,drcDataLen,"FileFeatureBits=",DRCFileFeatureBits) == false ) return false; //parse failed + if( parseDRCIntKey(drcData,drcDataLen,"FileFeatureBitsEssential=",DRCEssentialFileFeatureBits) == false ) return false; //parse failed } else//older format, set it based on knowledge: { @@ -261,33 +261,33 @@ smbool parseDRCInfo( const smuint8 *drcData, const int drcDataLen, int *DRCVersi //extra sanity check if( *numParams<1 || *numParams>1000 ) - return smfalse; + return false; //extra sanity check if( *DRCVersion<110 || *DRCVersion>10000 ) //110 is lowest released drc version - return smfalse; + return false; - return smtrue; + return true; } -smbool parseParameter( const smuint8 *drcData, const int drcDataLen, int idx, Parameter *param ) +bool parseParameter( const smuint8 *drcData, const int drcDataLen, int idx, Parameter *param ) { char line[maxLineLen]; char scanline[maxLineLen]; - smbool gotaddr=smfalse,gotvalue=smfalse, gotreadonly=smfalse, gotscale=smfalse,gotoffset=smfalse; + bool gotaddr=false,gotvalue=false, gotreadonly=false, gotscale=false,gotoffset=false; unsigned int readbytes; int readPosition=0; - smbool eof; + bool eof; //optimization below: finds starting offset where the wanted idx parameter will be available in drcData. //i.e. find start offset of line that starts with "50\" (for idx=50) if(idx>999) - return smfalse;//parseParam supports only idx 1-999 because startingTag has fixed length + return false;//parseParam supports only idx 1-999 because startingTag has fixed length char startingTag[6]; sprintf(startingTag,"\n%d\\",idx); readPosition=findSubstring(drcData,drcDataLen,startingTag); if(readPosition<0)//such parameter not found in data - return smfalse; + return false; do//loop trhu all lines of file { @@ -299,48 +299,48 @@ smbool parseParameter( const smuint8 *drcData, const int drcDataLen, int idx, Pa sprintf(scanline,"%d\\addr=",idx); if(!strncmp(line,scanline,strlen(scanline)) && readbytes > strlen(scanline))//string starts with correct line if(stringToInt(line+strlen(scanline),¶m->address)==1)//parse number after the start of line - gotaddr=smtrue;//number parse success + gotaddr=true;//number parse success //try read value sprintf(scanline,"%d\\value=",idx); if(!strncmp(line,scanline,strlen(scanline)) && readbytes > strlen(scanline))//string starts with correct line if(stringToDouble(line+strlen(scanline),¶m->value)==1)//parse number after the start of line - gotvalue=smtrue;//number parse success + gotvalue=true;//number parse success //try read offset sprintf(scanline,"%d\\offset=",idx); if(!strncmp(line,scanline,strlen(scanline)) && readbytes > strlen(scanline))//string starts with correct line if(stringToDouble(line+strlen(scanline),¶m->offset)==1)//parse number after the start of line - gotoffset=smtrue;//number parse success + gotoffset=true;//number parse success //try read scale sprintf(scanline,"%d\\scaling=",idx); if(!strncmp(line,scanline,strlen(scanline)) && readbytes > strlen(scanline))//string starts with correct line if(stringToDouble(line+strlen(scanline),¶m->scale)==1)//parse number after the start of line - gotscale=smtrue;//number parse success + gotscale=true;//number parse success //try read readonly status sprintf(scanline,"%d\\readonly=true",idx);//check if readonly=true if(!strncmp(line,scanline,strlen(scanline)) && readbytes >= strlen(scanline))//line match { - param->readOnly=smtrue; - gotreadonly=smtrue; + param->readOnly=true; + gotreadonly=true; } sprintf(scanline,"%d\\readonly=false",idx);//check if readonly=false if(!strncmp(line,scanline,strlen(scanline)) && readbytes >= strlen(scanline))//line match { - param->readOnly=smfalse; - gotreadonly=smtrue; + param->readOnly=false; + gotreadonly=true; } } - while( (gotvalue==smfalse || gotaddr==smfalse || gotreadonly==smfalse || gotscale==smfalse || gotoffset==smfalse) && eof==smfalse ); + while( (gotvalue==false || gotaddr==false || gotreadonly==false || gotscale==false || gotoffset==false) && eof==false ); - if(gotvalue==smtrue&&gotaddr==smtrue&&gotoffset==smtrue&&gotscale==smtrue&&gotreadonly==smtrue) + if(gotvalue==true&&gotaddr==true&&gotoffset==true&&gotscale==true&&gotreadonly==true) { - return smtrue; + return true; } - return smfalse;//not found + return false;//not found } /** @@ -359,7 +359,7 @@ LoadConfigurationStatus smLoadConfiguration(const smbus smhandle, const int smad smuint8 *drcData=NULL; int drcDataLength; - if(loadBinaryFile(filename,&drcData,&drcDataLength,smtrue)!=smtrue) + if(loadBinaryFile(filename,&drcData,&drcDataLength,true)!=true) return CFGUnableToOpenFile; ret = smLoadConfigurationFromBuffer( smhandle, smaddress, drcData, drcDataLength, mode, skippedCount, errorCount ); @@ -394,10 +394,10 @@ LIB LoadConfigurationStatus smLoadConfigurationFromBuffer( const smbus smhandle, int DRCFileFeatureBits, DRCEssentialFileFeatureBits; *skippedCount=-1; *errorCount=-1; - smbool deviceDisabled=smfalse; + bool deviceDisabled=false; //parse DRC header - if(parseDRCInfo(drcData,drcDataLength,&DRCVersion,&numParams,&DRCFileFeatureBits,&DRCEssentialFileFeatureBits)!=smtrue) + if(parseDRCInfo(drcData,drcDataLength,&DRCVersion,&numParams,&DRCFileFeatureBits,&DRCEssentialFileFeatureBits)!=true) return CFGInvalidFile; //check if essential bits have something that is not in feature bits (file sanity check error) @@ -427,21 +427,21 @@ LIB LoadConfigurationStatus smLoadConfigurationFromBuffer( const smbus smhandle, smDebug(smhandle,SMDebugLow,"Setting parameters\n"); - smbool readOk; + bool readOk; int i; for( i=1; i=size)//finished @@ -1012,7 +1012,7 @@ smbool flashFirmwarePrimaryMCU( smbus smhandle, int deviceaddress, const smuint8 { state=Init; *progress=0; - return smfalse; + return false; } if(faults&FLT_FLASHING_COMMSIDE_FAIL) @@ -1023,7 +1023,7 @@ smbool flashFirmwarePrimaryMCU( smbus smhandle, int deviceaddress, const smuint8 *progress=0; state=Init; - return smfalse; + return false; } else { @@ -1035,7 +1035,7 @@ smbool flashFirmwarePrimaryMCU( smbus smhandle, int deviceaddress, const smuint8 state=Init; } - return smtrue; + return true; } @@ -1062,25 +1062,25 @@ FirmwareUploadStatus smFirmwareUpload( const smbus smhandle, const int smaddress { static smuint8 *fwData=NULL; static int fwDataLength; - static smbool fileLoaded=smfalse; + static bool fileLoaded=false; FirmwareUploadStatus state; //load file to buffer if not loaded yet - if(fileLoaded==smfalse) + if(fileLoaded==false) { - if(loadBinaryFile(firmware_filename,&fwData,&fwDataLength,smfalse)!=smtrue) + if(loadBinaryFile(firmware_filename,&fwData,&fwDataLength,false)!=true) return FWFileNotReadable; - fileLoaded=smtrue; + fileLoaded=true; } //update FW, called multiple times per upgrade state=smFirmwareUploadFromBuffer( smhandle, smaddress, fwData, fwDataLength ); //if process complete, due to finish or error -> unload file. - if(((int)state<0 || state==FWComplete) && fileLoaded==smtrue) + if(((int)state<0 || state==FWComplete) && fileLoaded==true) { free(fwData); - fileLoaded=smfalse; + fileLoaded=false; } return state; @@ -1103,7 +1103,7 @@ FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int static smint32 deviceType=0; static int DFUAddress; static int progress=0; - static smbool FW_already_installed=smfalse; + static bool FW_already_installed=false; SM_STATUS stat; @@ -1137,13 +1137,13 @@ FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int //all good, upload firmware, unless state is changed to StatLaunch later state=StatFirstConnectAttempt; - FW_already_installed=smfalse; + FW_already_installed=false; //check if that FW is already installed if(GDFFileUID!=0)//check only if GDF has provided this value { smuint32 targetFWUID; - if(smGetDeviceFirmwareUniqueID( smhandle, smaddress, &targetFWUID )==smtrue) + if(smGetDeviceFirmwareUniqueID( smhandle, smaddress, &targetFWUID )==true) { //reset two upper bits because reading SMP will sign-extend them from 30 bits assuming so that we're reading signed 30 bit integer. //but this is unsigned 30 bit so reset top 2 bits to cancel sign extension. @@ -1169,7 +1169,7 @@ FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int state=StatLaunch;//launch app from DFU mode } - FW_already_installed=smtrue; + FW_already_installed=true; } else smDebug(smhandle,SMDebugLow,"smFirmwareUploadFromBuffer: firmware differs from the file (file UID %d, installed UID %d), uploading\n",GDFFileUID,targetFWUID); @@ -1269,8 +1269,8 @@ FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int { smDebug(smhandle,SMDebugMid,"smFirmwareUploadFromBuffer: StatUpload\n"); - smbool ret=flashFirmwarePrimaryMCU(smhandle,DFUAddress,fwData+primaryMCUDataOffset,primaryMCUDataLenth,&progress); - if(ret==smfalse)//failed + bool ret=flashFirmwarePrimaryMCU(smhandle,DFUAddress,fwData+primaryMCUDataOffset,primaryMCUDataLenth,&progress); + if(ret==false)//failed { smDebug(smhandle,SMDebugLow,"smFirmwareUploadFromBuffer: StatUpload failed\n"); return abortFWUpload(FWConnectionError,&state,1000); diff --git a/devicedeployment.h b/devicedeployment.h index e3fc325..d151579 100644 --- a/devicedeployment.h +++ b/devicedeployment.h @@ -151,9 +151,9 @@ LIB LoadConfigurationStatus smLoadConfigurationFromBuffer(const smbus smhandle, * @param smhandle SM bus handle, must be opened before call * @param smaddress Target SM device address. Can be device in DFU mode or main operating mode. For Argon, one device in a bus must be started into DFU mode by DIP switches and smaddress must be set to 255. * @param UID result will be written to this pointer - * @return smtrue if success, smfalse if failed (if communication otherwise works, then probably UID feature not present in this firmware version) + * @return true if success, false if failed (if communication otherwise works, then probably UID feature not present in this firmware version) */ -smbool smGetDeviceFirmwareUniqueID( smbus smhandle, int deviceaddress, smuint32 *UID ); +bool smGetDeviceFirmwareUniqueID( smbus smhandle, int deviceaddress, smuint32 *UID ); #ifdef __cplusplus diff --git a/simplemotion.c b/simplemotion.c index b63c629..9e0afae 100644 --- a/simplemotion.c +++ b/simplemotion.c @@ -29,14 +29,14 @@ FILE *smDebugOut=NULL; #define bufget8bit(buf, pos) (*((smuint8*)(smuint8*)((buf)+(pos)))) -smbool smIsHandleOpen( const smbus handle ); +bool smIsHandleOpen( const smbus handle ); SM_STATUS smReceiveReturnPacket( smbus bushandle ); typedef struct SM_BUS_ { smbusdevicehandle bdHandle; - smbool opened; + bool opened; enum RecvState recv_state,recv_state_next; @@ -47,8 +47,8 @@ typedef struct SM_BUS_ smuint8 recv_addr; smuint16 recv_crc; smuint16 recv_read_crc_hi; - smbool receiveComplete; - smbool transmitBufFull;//set true if user uploads too much commands in one SM transaction. if true, on execute commands, nothing will be sent to bus to prevent unvanted clipped commands and buffer will be cleared + bool receiveComplete; + bool transmitBufFull;//set true if user uploads too much commands in one SM transaction. if true, on execute commands, nothing will be sent to bus to prevent unvanted clipped commands and buffer will be cleared char busDeviceName[SM_BUSDEVICENAME_LEN]; smint16 cmd_send_queue_bytes;//for queued device commands @@ -63,7 +63,7 @@ SM_BUS smBus[SM_MAX_BUSES]; smuint16 readTimeoutMs=SM_READ_TIMEOUT; //init on first smOpenBus call -smbool smInitialized=smfalse; +bool smInitialized=false; //if debug message has priority this or above will be printed to debug stream smVerbosityLevel smDebugThreshold=SMDebugTrace; @@ -106,7 +106,7 @@ void smDebug( smbus handle, smVerbosityLevel verbositylevel, char *format, ...) va_end(fmtargs); if(handle>=0) { - if(smIsHandleOpen(handle)==smtrue) + if(smIsHandleOpen(handle)==true) { fprintf(smDebugOut,"%s: %s",smBus[handle].busDeviceName, buffer); } @@ -139,8 +139,8 @@ void smResetSM485variables(smbus handle) smBus[handle].recv_addr=255; smBus[handle].recv_crc=SM485_CRCINIT; smBus[handle].recv_read_crc_hi=0xffff;//bottom bits will be contains only 1 byte when read - smBus[handle].receiveComplete=smfalse; - smBus[handle].transmitBufFull=smfalse; + smBus[handle].receiveComplete=false; + smBus[handle].transmitBufFull=false; smBus[handle].cmd_send_queue_bytes=0; smBus[handle].cmd_recv_queue_bytes=0; } @@ -206,16 +206,16 @@ void smBusesInit() int i; for(i=0;i=SM_MAX_BUSES) return smfalse; + if(handle<0) return false; + if(handle>=SM_MAX_BUSES) return false; return smBus[handle].opened; } @@ -229,13 +229,13 @@ smbus smOpenBus( const char * devicename ) int handle; //true on first call - if(smInitialized==smfalse) + if(smInitialized==false) smBusesInit(); //find free handle for(handle=0;handle=SM_MAX_BUSES) return -1; @@ -247,7 +247,7 @@ smbus smOpenBus( const char * devicename ) //success strncpy( smBus[handle].busDeviceName, devicename, SM_BUSDEVICENAME_LEN ); smBus[handle].busDeviceName[SM_BUSDEVICENAME_LEN-1]=0;//null terminate string - smBus[handle].opened=smtrue; + smBus[handle].opened=true; return handle; } @@ -257,13 +257,13 @@ smbus smOpenBusWithCallbacks( const char *devicename, BusdeviceOpen busOpenCallb int handle; //true on first call - if(smInitialized==smfalse) + if(smInitialized==false) smBusesInit(); //find free handle for(handle=0;handle=SM_MAX_BUSES) return -1; @@ -275,7 +275,7 @@ smbus smOpenBusWithCallbacks( const char *devicename, BusdeviceOpen busOpenCallb //success strncpy( smBus[handle].busDeviceName, devicename, SM_BUSDEVICENAME_LEN ); smBus[handle].busDeviceName[SM_BUSDEVICENAME_LEN-1]=0;//null terminate string - smBus[handle].opened=smtrue; + smBus[handle].opened=true; return handle; } @@ -307,11 +307,11 @@ LIB void smSetBaudrate( unsigned long pbs ) LIB SM_STATUS smCloseBus( const smbus bushandle ) { //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==smfalse) return recordStatus(bushandle,SM_ERR_NODEVICE); + if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); - smBus[bushandle].opened=smfalse; + smBus[bushandle].opened=false; - if( smBDClose(smBus[bushandle].bdHandle) == smfalse ) return recordStatus(bushandle,SM_ERR_BUS); + if( smBDClose(smBus[bushandle].bdHandle) == false ) return recordStatus(bushandle,SM_ERR_BUS); return SM_OK; } @@ -322,9 +322,9 @@ LIB SM_STATUS smCloseBus( const smbus bushandle ) LIB SM_STATUS smPurge( const smbus bushandle ) { //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==smfalse) return recordStatus(bushandle,SM_ERR_NODEVICE); + if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); - if(smBDMiscOperation( bushandle, MiscOperationPurgeRX )==smtrue) + if(smBDMiscOperation( bushandle, MiscOperationPurgeRX )==true) return recordStatus(bushandle,SM_OK); else return recordStatus(bushandle,SM_ERR_BUS); @@ -336,9 +336,9 @@ LIB SM_STATUS smPurge( const smbus bushandle ) LIB SM_STATUS smFlushTX( const smbus bushandle ) { //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==smfalse) return recordStatus(bushandle,SM_ERR_NODEVICE); + if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); - if(smBDMiscOperation( bushandle, MiscOperationFlushTX )==smtrue) + if(smBDMiscOperation( bushandle, MiscOperationFlushTX )==true) return recordStatus(bushandle,SM_OK); else return recordStatus(bushandle,SM_ERR_BUS); @@ -372,12 +372,12 @@ char *cmdidToStr(smuint8 cmdid ) //write one byte to tx buffer //returns true on success -smbool smWriteByte( const smbus handle, const smuint8 byte, smuint16 *crc ) +bool smWriteByte( const smbus handle, const smuint8 byte, smuint16 *crc ) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; - smbool success=smBDWrite(smBus[handle].bdHandle,byte); + bool success=smBDWrite(smBus[handle].bdHandle,byte); if(crc!=NULL) *crc = calcCRC16(byte,*crc); @@ -386,12 +386,12 @@ smbool smWriteByte( const smbus handle, const smuint8 byte, smuint16 *crc ) //write tx buffer to bus //returns true on success -smbool smTransmitBuffer( const smbus handle ) +bool smTransmitBuffer( const smbus handle ) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; - smbool success=smBDTransmit(smBus[handle].bdHandle); + bool success=smBDTransmit(smBus[handle].bdHandle); return success; } @@ -401,7 +401,7 @@ SM_STATUS smSendSMCMD( smbus handle, smuint8 cmdid, smuint8 addr, smuint8 datale smuint16 sendcrc; //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; sendcrc=SM485_CRCINIT; @@ -411,30 +411,30 @@ SM_STATUS smSendSMCMD( smbus handle, smuint8 cmdid, smuint8 addr, smuint8 datale smDebug(handle,SMDebugHigh," Outbound packet raw data: CMDID (%d) ",cmdid); - if( smWriteByte(handle,cmdid, &sendcrc) != smtrue ) return recordStatus(handle,SM_ERR_BUS); + if( smWriteByte(handle,cmdid, &sendcrc) != true ) return recordStatus(handle,SM_ERR_BUS); if(cmdid&SMCMD_MASK_N_PARAMS) { smDebug(DEBUG_PRINT_RAW,SMDebugHigh,"SIZE (%d bytes) ", datalen); - if( smWriteByte(handle,datalen, &sendcrc) != smtrue ) return recordStatus(handle,SM_ERR_BUS); + if( smWriteByte(handle,datalen, &sendcrc) != true ) return recordStatus(handle,SM_ERR_BUS); } smDebug(DEBUG_PRINT_RAW,SMDebugHigh,"ADDR (%d) ",addr); - if( smWriteByte(handle,addr, &sendcrc) != smtrue ) return recordStatus(handle,SM_ERR_BUS); + if( smWriteByte(handle,addr, &sendcrc) != true ) return recordStatus(handle,SM_ERR_BUS); smDebug(DEBUG_PRINT_RAW,SMDebugHigh,"PAYLOAD ("); for(i=0;i>8, sendcrc&0xff); - if( smWriteByte(handle,sendcrc>>8, NULL) != smtrue ) return recordStatus(handle,SM_ERR_BUS); - if( smWriteByte(handle,sendcrc&0xff,NULL) != smtrue ) return recordStatus(handle,SM_ERR_BUS); + if( smWriteByte(handle,sendcrc>>8, NULL) != true ) return recordStatus(handle,SM_ERR_BUS); + if( smWriteByte(handle,sendcrc&0xff,NULL) != true ) return recordStatus(handle,SM_ERR_BUS); //transmit bytes to bus that were written in buffer by smWriteByte calls - if( smTransmitBuffer(handle) != smtrue ) return recordStatus(handle,SM_ERR_BUS); + if( smTransmitBuffer(handle) != true ) return recordStatus(handle,SM_ERR_BUS); return recordStatus(handle,SM_OK); } @@ -448,7 +448,7 @@ LIB SM_STATUS smFastUpdateCycleWithStructs( smbus handle, smuint8 nodeAddress, F SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, smuint16 write2, smuint16 *read1, smuint16 *read2) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; smDebug(handle, SMDebugHigh, "> %s (addr=%d, w1=%d, w2=%d)\n",cmdidToStr(SMCMD_FAST_UPDATE_CYCLE), nodeAddress, @@ -467,7 +467,7 @@ SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, //send for(i=0;i<7;i++) { - if( smWriteByte(handle,cmd[i], NULL) != smtrue ) + if( smWriteByte(handle,cmd[i], NULL) != true ) return recordStatus(handle,SM_ERR_BUS); } smTransmitBuffer(handle);//this sends the bytes entered with smWriteByte @@ -475,11 +475,11 @@ SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, smDebug(handle, SMDebugHigh, " Reading reply packet\n"); for(i=0;i<6;i++) { - smbool success; + bool success; smuint8 rx; success=smBDRead(smBus[handle].bdHandle,&rx); cmd[i]=rx; - if(success!=smtrue) + if(success!=true) { smDebug(handle,SMDebugLow,"Not enough data received on smFastUpdateCycle"); return recordStatus(handle,SM_ERR_BUS|SM_ERR_LENGTH);//no enough data received @@ -508,23 +508,23 @@ SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, -SM_STATUS smReceiveErrorHandler( smbus handle, smbool flushrx ) +SM_STATUS smReceiveErrorHandler( smbus handle, bool flushrx ) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; //empty pending rx buffer to avoid further parse errors - if(flushrx==smtrue) + if(flushrx==true) { - smbool success; + bool success; do{ smuint8 rx; success=smBDRead(smBus[handle].bdHandle,&rx); - }while(success==smtrue); + }while(success==true); } smResetSM485variables(handle); - smBus[handle].receiveComplete=smtrue; + smBus[handle].receiveComplete=true; return recordStatus(handle,SM_ERR_COMMUNICATION); } @@ -534,7 +534,7 @@ SM_STATUS smAppendSMCommandToQueue( smbus handle, int smpCmdType,smint32 paramva int cmdlength; //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; switch(smpCmdType) { @@ -555,7 +555,7 @@ SM_STATUS smAppendSMCommandToQueue( smbus handle, int smpCmdType,smint32 paramva //check if space if buffer if(smBus[handle].cmd_send_queue_bytes>(SM485_MAX_PAYLOAD_BYTES-cmdlength) ) { - smBus[handle].transmitBufFull=smtrue; //when set true, smExecute will do nothing but clear transmit buffer. so this prevents any of overflowed commands getting thru + smBus[handle].transmitBufFull=true; //when set true, smExecute will do nothing but clear transmit buffer. so this prevents any of overflowed commands getting thru return recordStatus(handle,SM_ERR_LENGTH); //overflow, too many commands in buffer } @@ -606,9 +606,9 @@ SM_STATUS smTransmitReceiveCommandQueue( const smbus bushandle, const smaddr tar SM_STATUS stat; //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==smfalse) return recordStatus(bushandle,SM_ERR_NODEVICE); + if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); - if(smBus[bushandle].transmitBufFull!=smtrue) //dont send/receive commands if queue was overflowed by user error + if(smBus[bushandle].transmitBufFull!=true) //dont send/receive commands if queue was overflowed by user error { stat=smSendSMCMD(bushandle,cmdid,targetaddress, smBus[bushandle].cmd_send_queue_bytes, smBus[bushandle].recv_rsbuf ); //send commands to bus if(stat!=SM_OK) return recordStatus(bushandle,stat); @@ -617,7 +617,7 @@ SM_STATUS smTransmitReceiveCommandQueue( const smbus bushandle, const smaddr tar smBus[bushandle].cmd_send_queue_bytes=0; smBus[bushandle].cmd_recv_queue_bytes=0;//counted upwards at every smGetQueued.. and compared to payload size - if(smBus[bushandle].transmitBufFull!=smtrue && targetaddress!=0)//dont send/receive commands if queue was overflowed by user error, or if target is broadcast address (0) where no slave will respond and it's ok + if(smBus[bushandle].transmitBufFull!=true && targetaddress!=0)//dont send/receive commands if queue was overflowed by user error, or if target is broadcast address (0) where no slave will respond and it's ok { stat=smReceiveReturnPacket(bushandle);//blocking wait & receive return values from bus if(stat!=SM_OK) return recordStatus(bushandle,stat); //maybe timeouted @@ -625,11 +625,11 @@ SM_STATUS smTransmitReceiveCommandQueue( const smbus bushandle, const smaddr tar if(targetaddress==0) { //make sure we don't return function before all data is really sent as we're not waiting for RX data - //note: we're note checking return value of it as some driver's dont support this atm and will return smfalse. TODO fix this & drivers. + //note: we're note checking return value of it as some driver's dont support this atm and will return false. TODO fix this & drivers. smFlushTX(bushandle); } - smBus[bushandle].transmitBufFull=smfalse;//reset overflow status + smBus[bushandle].transmitBufFull=false;//reset overflow status return recordStatus(bushandle,SM_OK); } @@ -637,7 +637,7 @@ SM_STATUS smTransmitReceiveCommandQueue( const smbus bushandle, const smaddr tar SM_STATUS smExecuteCommandQueue( const smbus bushandle, const smaddr targetaddress ) { //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(bushandle)==false) return SM_ERR_NODEVICE; return recordStatus(bushandle,smTransmitReceiveCommandQueue(bushandle,targetaddress,SMCMD_INSTANT_CMD)); } @@ -650,7 +650,7 @@ SM_STATUS smUploadCommandQueueToDeviceBuffer( const smbus bushandle, const smadd //return number of how many bytes waiting to be read with smGetQueuedSMCommandReturnValue SM_STATUS smBytesReceived( const smbus bushandle, smint32 *bytesinbuffer ) { - if(smIsHandleOpen(bushandle)==smfalse) return recordStatus(bushandle,SM_ERR_NODEVICE); + if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); smint32 bytes=smBus[bushandle].recv_payloadsize - smBus[bushandle].cmd_recv_queue_bytes;//how many bytes waiting to be read with smGetQueuedSMCommandReturnValue *bytesinbuffer=bytes; @@ -663,7 +663,7 @@ SM_STATUS smGetQueuedSMCommandReturnValue( const smbus bushandle, smint32 *retV smuint8 rxbyte, rettype; //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(bushandle)==false) return SM_ERR_NODEVICE; //if get called so many times that receive queue buffer is already empty, return error @@ -742,7 +742,7 @@ SM_STATUS smGetQueuedSMCommandReturnValue( const smbus bushandle, smint32 *retV SM_STATUS smReceiveReturnPacket( smbus bushandle ) { //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(bushandle)==false) return SM_ERR_NODEVICE; smDebug(bushandle, SMDebugHigh, " Reading reply packet\n"); do @@ -750,17 +750,17 @@ SM_STATUS smReceiveReturnPacket( smbus bushandle ) smuint8 ret; SM_STATUS stat; - smbool succ=smBDRead(smBus[bushandle].bdHandle,&ret); + bool succ=smBDRead(smBus[bushandle].bdHandle,&ret); - if(succ==smfalse) + if(succ==false) { - smReceiveErrorHandler(bushandle,smfalse); + smReceiveErrorHandler(bushandle,false); return recordStatus(bushandle,SM_ERR_COMMUNICATION); } stat=smParseReturnData( bushandle, ret ); if(stat!=SM_OK) return recordStatus(bushandle,stat); - } while(smBus[bushandle].receiveComplete==smfalse); //loop until complete packaget has been read + } while(smBus[bushandle].receiveComplete==false); //loop until complete packaget has been read //return data read complete smDebug(bushandle,SMDebugHigh, "< %s (id=%d, addr=%d, payload=%d)\n", @@ -786,11 +786,11 @@ LIB void smSetDebugOutput( smVerbosityLevel level, FILE *stream ) SM_STATUS smParseReturnData( smbus handle, smuint8 data ) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; //buffered variable allows placing if's in any order (because recv_state may changes in this function) smBus[handle].recv_state=smBus[handle].recv_state_next; - smBus[handle].receiveComplete=smfalse;//overwritten to true later if complete + smBus[handle].receiveComplete=false;//overwritten to true later if complete if(smBus[handle].recv_state==WaitPayload) { @@ -801,7 +801,7 @@ SM_STATUS smParseReturnData( smbus handle, smuint8 data ) smBus[handle].recv_rsbuf[smBus[handle].recv_storepos++]=data; else//rx payload buffer overflow { - return recordStatus(handle,(smReceiveErrorHandler(handle,smtrue))); + return recordStatus(handle,(smReceiveErrorHandler(handle,true))); } //all received @@ -822,7 +822,7 @@ SM_STATUS smParseReturnData( smbus handle, smuint8 data ) case SMCMD_MASK_0_PARAMS: smBus[handle].recv_payloadsize=0; smBus[handle].recv_state_next=WaitAddr; break; case SMCMD_MASK_N_PARAMS: smBus[handle].recv_payloadsize=-1; smBus[handle].recv_state_next=WaitPayloadSize;break;//-1 = N databytes default: - return recordStatus(handle,(smReceiveErrorHandler(handle, smtrue))); + return recordStatus(handle,(smReceiveErrorHandler(handle, true))); break; //error, unsupported command id } @@ -862,13 +862,13 @@ SM_STATUS smParseReturnData( smbus handle, smuint8 data ) if(((smBus[handle].recv_read_crc_hi<<8)|data)!=smBus[handle].recv_crc) { //CRC error - return recordStatus(handle,(smReceiveErrorHandler(handle,smtrue))); + return recordStatus(handle,(smReceiveErrorHandler(handle,true))); } else { //CRC ok //if(smBus[handle].recv_addr==config.deviceAddress || smBus[handle].recv_cmdid==SMCMD_GET_CLOCK_RET || smBus[handle].recv_cmdid==SMCMD_PROCESS_IMAGE ) executeSMcmd(); - smBus[handle].receiveComplete=smtrue; + smBus[handle].receiveComplete=true; } //smResetSM485variables(handle); @@ -888,7 +888,7 @@ SM_STATUS smAppendGetParamCommandToQueue( smbus handle, smint16 paramAddress ) SM_STATUS stat=SM_NONE; //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; //possible errors will set bits to stat stat|=smAppendSMCommandToQueue( handle, SMPCMD_SETPARAMADDR, SMP_RETURN_PARAM_LEN ); //2b @@ -906,7 +906,7 @@ SM_STATUS smGetQueuedGetParamReturnValue( const smbus bushandle, smint32 *retVa SM_STATUS stat=SM_NONE; //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(bushandle)==false) return SM_ERR_NODEVICE; //must get all inserted commands from buffer stat|=smGetQueuedSMCommandReturnValue( bushandle, &retVal );//4x4b @@ -923,7 +923,7 @@ SM_STATUS smAppendSetParamCommandToQueue( smbus handle, smint16 paramAddress, sm SM_STATUS stat=SM_NONE; //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; stat|=smAppendSMCommandToQueue( handle, SMPCMD_SETPARAMADDR, paramAddress );//2b stat|=smAppendSMCommandToQueue( handle, SMPCMD_32B, paramValue );//4b @@ -937,7 +937,7 @@ SM_STATUS smGetQueuedSetParamReturnValue( const smbus bushandle, smint32 *retVa SM_STATUS stat=SM_NONE; //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(bushandle)==false) return SM_ERR_NODEVICE; //must get all inserted commands from buffer stat|=smGetQueuedSMCommandReturnValue( bushandle, &retVal ); @@ -955,7 +955,7 @@ SM_STATUS smGetBufferClock( const smbus handle, const smaddr targetaddr, smuint1 smDebug(handle,SMDebugMid,"smGetBufferClock: target SM address %d.\n",(int)targetaddr); //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==smfalse) return recordStatus(handle,SM_ERR_NODEVICE); + if(smIsHandleOpen(handle)==false) return recordStatus(handle,SM_ERR_NODEVICE); stat=smSendSMCMD(handle, SMCMD_GET_CLOCK ,targetaddr, 0, NULL ); //send get clock commands to bus if(stat!=SM_OK) return recordStatus(handle,stat); @@ -1056,7 +1056,7 @@ SM_STATUS smSetParameter( const smbus handle, const smaddr nodeAddress, const sm SM_STATUS recordStatus( const smbus handle, const SM_STATUS stat ) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; if(smBus[handle].cumulativeSmStatus!=stat && stat!=SM_OK)//if status changed and new status is not SM_OK smDebug(handle,SMDebugLow,"Previous SM call failed and changed the SM_STATUS value obtainable with getCumulativeStatus(). Status before failure was %d, and new error flag valued %d has been now set.\n",(int)smBus[handle].cumulativeSmStatus,(int)stat); @@ -1070,7 +1070,7 @@ SM_STATUS recordStatus( const smbus handle, const SM_STATUS stat ) /** This function returns all occurred SM_STATUS bits after smOpenBus or resetCumulativeStatus call*/ SM_STATUS getCumulativeStatus( const smbus handle ) { - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; return smBus[handle].cumulativeSmStatus; } @@ -1078,7 +1078,7 @@ SM_STATUS getCumulativeStatus( const smbus handle ) /** Reset cululative status so getCumultiveStatus returns 0 after calling this until one of the other functions are called*/ SM_STATUS resetCumulativeStatus( const smbus handle ) { - if(smIsHandleOpen(handle)==smfalse) return SM_ERR_NODEVICE; + if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; smDebug(handle,SMDebugMid,"resetCumulativeStatus called.\n"); @@ -1113,9 +1113,9 @@ smint smGetNumberOfDetectedBuses() */ LIB SM_STATUS smGetBusDeviceDetails( smint index, SM_BUS_DEVICE_INFO *info ) { - smbool ok=smBDGetBusDeviceDetails(index,info); + bool ok=smBDGetBusDeviceDetails(index,info); - if(ok==smtrue) + if(ok==true) return SM_OK; else return SM_ERR_NODEVICE; @@ -1282,11 +1282,11 @@ LIB int smDescribeStatus(char* str, const size_t size, int32_t status) LIB SM_STATUS smCheckDeviceCapabilities(const smbus handle, const int nodeAddress, const smint32 capabilitiesParameterNr, const smint32 requiredCapabilityFlags, - smbool *resultHasAllCapabilities ) + bool *resultHasAllCapabilities ) { SM_STATUS smStat=0; smint32 SMProtocolVersion; - *resultHasAllCapabilities=smfalse;//set true later + *resultHasAllCapabilities=false;//set true later smStat|=smRead1Parameter(handle,nodeAddress,SMP_SM_VERSION,&SMProtocolVersion); if(smStat!=SM_OK) return smStat; //error in above call @@ -1301,7 +1301,7 @@ LIB SM_STATUS smCheckDeviceCapabilities(const smbus handle, const int nodeAddres if(smStat!=SM_OK) return smStat; //error in above call if( (capabilities&requiredCapabilityFlags)==requiredCapabilityFlags )//if all required capabilities are supported - *resultHasAllCapabilities=smtrue;//set result + *resultHasAllCapabilities=true;//set result return SM_OK; } @@ -1326,7 +1326,7 @@ LIB SM_STATUS smCheckDeviceCapabilities(const smbus handle, const int nodeAddres if(smStat!=SM_OK) return smStat; //error in above call if( (capabilities&requiredCapabilityFlags)==requiredCapabilityFlags )//if all required capabilities are supported - *resultHasAllCapabilities=smtrue;//set result + *resultHasAllCapabilities=true;//set result return SM_OK; } diff --git a/simplemotion.h b/simplemotion.h index 073bf17..b0bce2f 100644 --- a/simplemotion.h +++ b/simplemotion.h @@ -27,7 +27,7 @@ extern "C"{ #endif -//BusdeviceOpen callback should return this if port open fails (in addition to setting *success to smfalse): +//BusdeviceOpen callback should return this if port open fails (in addition to setting *success to false): #define SMBUSDEVICE_RETURN_ON_OPEN_FAIL NULL @@ -256,14 +256,14 @@ LIB int smDescribeStatus(char* str, size_t size, int32_t status); /** smCheckDeviceCapabilities will check whether target device has all requested capabilities. * * I.e. code: - * smbool resultHasAllCapabilities; + * bool resultHasAllCapabilities; * smCheckDeviceCapabilities( handle, nodeAddress, SMP_DEVICE_CAPABILITIES1, DEVICE_CAPABILITY1_AUTOSETUP_COMMUTATION_SENSOR|DEVICE_CAPABILITY1_BUFFERED_MOTION_LINEAR_INTERPOLATION, &resultHasAllCapabilities ); * Will check whether device supports DEVICE_CAPABILITY1_AUTOSETUP_COMMUTATION_SENSOR and DEVICE_CAPABILITY1_BUFFERED_MOTION_LINEAR_INTERPOLATION. - * If it supports both, resultHasAllCapabilities will be set smtrue, otherwise it will be set smfalse. + * If it supports both, resultHasAllCapabilities will be set true, otherwise it will be set false. * * Note: be careful to enter correct SMP_DEVICE_CAPABILITIESn parameter and correct DEVICE_CAPBILITYn flags as arguments as there is no checking for correctness. * I.e. passing argument SMP_DEVICE_CAPABILITIES1 and flags DEVICE_CAPABILITY1_AUTOSETUP_COMMUTATION_SENSOR|DEVICE_CAPABILITY2_LOW_LEVEL_GPIO will return @@ -274,7 +274,7 @@ LIB int smDescribeStatus(char* str, size_t size, int32_t status); LIB SM_STATUS smCheckDeviceCapabilities( const smbus handle, const int nodeAddress, const smint32 capabilitiesParameterNr, const smint32 requiredCapabilityFlags, - smbool *resultHasAllCapabilities ); + bool *resultHasAllCapabilities ); #ifdef __cplusplus } diff --git a/simplemotion_types.h b/simplemotion_types.h index cd539ae..09523f2 100644 --- a/simplemotion_types.h +++ b/simplemotion_types.h @@ -24,8 +24,10 @@ typedef uint8_t smuint8; typedef int32_t smint32; typedef int16_t smint16; typedef int8_t smint8; -typedef int8_t smbool; typedef smint32 smint; +typedef bool smbool; + +// These are kept only for legacy compatibility; use for better versions #define smtrue 1 #define smfalse 0 typedef int SM_STATUS; @@ -34,7 +36,7 @@ typedef smuint8 smaddr; // output parameter type of smGetBusDeviceDetails typedef struct { - smbool is_simplemotion_device;//smtrue if usable in SM lib + bool is_simplemotion_device;//true if usable in SM lib char device_name[64];//name that should be fed to smOpenBus char description[128];//such as "SimpleMotion USB" } SM_BUS_DEVICE_INFO; @@ -52,20 +54,20 @@ typedef enum _smVerbosityLevel {SMDebugOff,SMDebugLow,SMDebugMid,SMDebugHigh,SMD * * MiscOperationFlushTX = blocking call to make sure that all data has been physically transmitter * before returing the function. Max blocking duration is the value set with smSetTimeout. - * If flush operation timeouted, return smfalse (fail), otherwise smtrue (success). - * MiscOperationPurgeRX = discard all incoming data that is waiting to be read. Return smtrue on success, - * smfalse on fail. + * If flush operation timeouted, return false (fail), otherwise true (success). + * MiscOperationPurgeRX = discard all incoming data that is waiting to be read. Return true on success, + * false on fail. * - * If operation is unsupported by the callback, return smfalse. + * If operation is unsupported by the callback, return false. */ typedef enum _BusDeviceMiscOperationType {MiscOperationFlushTX,MiscOperationPurgeRX} BusDeviceMiscOperationType; //define communication interface device driver callback types typedef void* smBusdevicePointer; -typedef smBusdevicePointer (*BusdeviceOpen)(const char *port_device_name, smint32 baudrate_bps, smbool *success); +typedef smBusdevicePointer (*BusdeviceOpen)(const char *port_device_name, smint32 baudrate_bps, bool *success); typedef smint32 (*BusdeviceReadBuffer)(smBusdevicePointer busdevicePointer, unsigned char *buf, smint32 size); typedef smint32 (*BusdeviceWriteBuffer)(smBusdevicePointer busdevicePointer, unsigned char *buf, smint32 size); -typedef smbool (*BusdeviceMiscOperation)(smBusdevicePointer busdevicePointer, BusDeviceMiscOperationType operation ); +typedef bool (*BusdeviceMiscOperation)(smBusdevicePointer busdevicePointer, BusDeviceMiscOperationType operation ); typedef void (*BusdeviceClose)(smBusdevicePointer busdevicePointer); //must use packed mode for bitfields in structs for smFastUpdateCycleWithStructs From f0e22c23e36594bf1d4ca3c633317cf33462c0cb Mon Sep 17 00:00:00 2001 From: Joonas Koivunen Date: Sat, 9 Nov 2019 20:50:30 +0200 Subject: [PATCH 03/11] refactor get rid of redundant x == true --- bufferedmotion.c | 8 ++++---- devicedeployment.c | 18 +++++++++--------- simplemotion.c | 12 ++++++------ 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/bufferedmotion.c b/bufferedmotion.c index 219e81f..07d44dc 100644 --- a/bufferedmotion.c +++ b/bufferedmotion.c @@ -79,10 +79,10 @@ SM_STATUS smBufferedDeinit( BufferedMotionAxis *axis ) smBufferedAbort(axis); //restore drive in pre-init state - if(axis->initialized==true) + if(axis->initialized) { smSetParameter(axis->bushandle,axis->deviceAddress,SMP_TRAJ_PLANNER_ACCEL,axis->driveAccelerationBeforeInit); - if(axis->driveFlagsModifiedAtInit==true)//if flags parameter modified, then restore the origianl value + if(axis->driveFlagsModifiedAtInit)//if flags parameter modified, then restore the origianl value smSetParameter(axis->bushandle,axis->deviceAddress,SMP_DRIVE_FLAGS,axis->driveFlagsBeforeInit); } @@ -124,7 +124,7 @@ smint32 smBufferedGetMaxFillSize(BufferedMotionAxis *axis, smint32 numBytesFree numBytesFree=SM485_MAX_PAYLOAD_BYTES; //calculate number of points that can be uploaded to buffer (max size SM485_MAX_PAYLOAD_BYTES bytes and fill consumption is 2+4+2+3*(n-1) bytes) - if(axis->readParamInitialized==true) + if(axis->readParamInitialized) //*numPoints=(freebytes-2-4-2)/3+1; return numBytesFree/4; else @@ -135,7 +135,7 @@ smint32 smBufferedGetMaxFillSize(BufferedMotionAxis *axis, smint32 numBytesFree smint32 smBufferedGetBytesConsumed(BufferedMotionAxis *axis, smint32 numFillPoints ) { //calculate number of bytes that the number of fill points will consume from buffer - if(axis->readParamInitialized==true) + if(axis->readParamInitialized) return numFillPoints*4; else return numFillPoints*4 +2+3+2+3+2;//if read data uninitialized, it takes extra n bytes to init on next fill, so reduce it here diff --git a/devicedeployment.c b/devicedeployment.c index c280c47..442c366 100755 --- a/devicedeployment.c +++ b/devicedeployment.c @@ -67,7 +67,7 @@ unsigned int readFileLine( const smuint8 *data, const int dataLen, int *readPosi } //eol or eof - if( (*eof)==true || c=='\n' || c=='\r' || len>=charlimit-1 ) + if(*eof || c=='\n' || c=='\r' || len>=charlimit-1) { output[len]=0;//terminate str return len; @@ -127,7 +127,7 @@ int decimalNumberToDouble( const char *str, double *output ) else if(number>=0 && number <=9) //is number { out=10.0*out+number; - if(decimalPointFound==true) + if(decimalPointFound) decimalcoeff*=0.1; } else if (c=='.')//is decimal point @@ -335,7 +335,7 @@ bool parseParameter( const smuint8 *drcData, const int drcDataLen, int idx, Para } while( (gotvalue==false || gotaddr==false || gotreadonly==false || gotscale==false || gotoffset==false) && eof==false ); - if(gotvalue==true&&gotaddr==true&&gotoffset==true&&gotscale==true&&gotreadonly==true) + if(gotvalue&&gotaddr&&gotoffset&&gotscale&&gotreadonly) { return true; } @@ -509,7 +509,7 @@ LIB LoadConfigurationStatus smLoadConfigurationFromBuffer( const smbus smhandle, { bool result; smCheckDeviceCapabilities( smhandle, smaddress, SMP_DEVICE_CAPABILITIES2, DEVICE_CAPABILITY2_SUPPORT_TRIGGER_PENDING_PARAMETER_ACTIVATION, &result); - if(result==true) + if(result) smSetParameter( smhandle, smaddress, SMP_SYSTEM_CONTROL, SMP_SYSTEM_CONTROL_TRIGGER_PENDING_PARAMETER_ACTIVATION ); } @@ -529,7 +529,7 @@ LIB LoadConfigurationStatus smLoadConfigurationFromBuffer( const smbus smhandle, } //re-enable drive - if(mode&CONFIGMODE_DISABLE_DURING_CONFIG && deviceDisabled==true) + if(mode&CONFIGMODE_DISABLE_DURING_CONFIG && deviceDisabled) { smDebug(smhandle,SMDebugLow,"Restoring CONTROL_BITS1 to value 0x%x\n",CB1Value); smSetParameter( smhandle, smaddress, SMP_CONTROL_BITS1, CB1Value );//restore controbits1 (enable if it was enabled before) @@ -866,7 +866,7 @@ bool loadBinaryFile(const char *filename, smuint8 **data, int *numbytes , bool a fseek(f,0,SEEK_SET); //allocate buffer - if(addNullTermination==true) + if(addNullTermination) *data=malloc(length+1);//+1 for 0 termination char else *data=malloc(length); @@ -877,7 +877,7 @@ bool loadBinaryFile(const char *filename, smuint8 **data, int *numbytes , bool a return false; } - if(addNullTermination==true) + if(addNullTermination) (*data)[length]=0;//add 0 termination character at the end, this 0 prevents parse function doing buffer overflow if file is corrupt //read @@ -1077,7 +1077,7 @@ FirmwareUploadStatus smFirmwareUpload( const smbus smhandle, const int smaddress state=smFirmwareUploadFromBuffer( smhandle, smaddress, fwData, fwDataLength ); //if process complete, due to finish or error -> unload file. - if(((int)state<0 || state==FWComplete) && fileLoaded==true) + if(((int)state<0 || state==FWComplete) && fileLoaded) { free(fwData); fileLoaded=false; @@ -1143,7 +1143,7 @@ FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int if(GDFFileUID!=0)//check only if GDF has provided this value { smuint32 targetFWUID; - if(smGetDeviceFirmwareUniqueID( smhandle, smaddress, &targetFWUID )==true) + if(smGetDeviceFirmwareUniqueID( smhandle, smaddress, &targetFWUID )) { //reset two upper bits because reading SMP will sign-extend them from 30 bits assuming so that we're reading signed 30 bit integer. //but this is unsigned 30 bit so reset top 2 bits to cancel sign extension. diff --git a/simplemotion.c b/simplemotion.c index 9e0afae..9567dc9 100644 --- a/simplemotion.c +++ b/simplemotion.c @@ -106,7 +106,7 @@ void smDebug( smbus handle, smVerbosityLevel verbositylevel, char *format, ...) va_end(fmtargs); if(handle>=0) { - if(smIsHandleOpen(handle)==true) + if(smIsHandleOpen(handle)) { fprintf(smDebugOut,"%s: %s",smBus[handle].busDeviceName, buffer); } @@ -324,7 +324,7 @@ LIB SM_STATUS smPurge( const smbus bushandle ) //check if bus handle is valid & opened if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); - if(smBDMiscOperation( bushandle, MiscOperationPurgeRX )==true) + if(smBDMiscOperation( bushandle, MiscOperationPurgeRX )) return recordStatus(bushandle,SM_OK); else return recordStatus(bushandle,SM_ERR_BUS); @@ -338,7 +338,7 @@ LIB SM_STATUS smFlushTX( const smbus bushandle ) //check if bus handle is valid & opened if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); - if(smBDMiscOperation( bushandle, MiscOperationFlushTX )==true) + if(smBDMiscOperation( bushandle, MiscOperationFlushTX )) return recordStatus(bushandle,SM_OK); else return recordStatus(bushandle,SM_ERR_BUS); @@ -515,13 +515,13 @@ SM_STATUS smReceiveErrorHandler( smbus handle, bool flushrx ) //empty pending rx buffer to avoid further parse errors - if(flushrx==true) + if(flushrx) { bool success; do{ smuint8 rx; success=smBDRead(smBus[handle].bdHandle,&rx); - }while(success==true); + }while(success); } smResetSM485variables(handle); smBus[handle].receiveComplete=true; @@ -1115,7 +1115,7 @@ LIB SM_STATUS smGetBusDeviceDetails( smint index, SM_BUS_DEVICE_INFO *info ) { bool ok=smBDGetBusDeviceDetails(index,info); - if(ok==true) + if(ok) return SM_OK; else return SM_ERR_NODEVICE; From 574ba07798c544f952dd58260d361da57009e871 Mon Sep 17 00:00:00 2001 From: Joonas Koivunen Date: Sat, 9 Nov 2019 20:53:33 +0200 Subject: [PATCH 04/11] refactor fix not true comparisons --- devicedeployment.c | 6 +++--- simplemotion.c | 22 +++++++++++----------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/devicedeployment.c b/devicedeployment.c index 442c366..f59b4ab 100755 --- a/devicedeployment.c +++ b/devicedeployment.c @@ -359,7 +359,7 @@ LoadConfigurationStatus smLoadConfiguration(const smbus smhandle, const int smad smuint8 *drcData=NULL; int drcDataLength; - if(loadBinaryFile(filename,&drcData,&drcDataLength,true)!=true) + if(!loadBinaryFile(filename,&drcData,&drcDataLength,true)) return CFGUnableToOpenFile; ret = smLoadConfigurationFromBuffer( smhandle, smaddress, drcData, drcDataLength, mode, skippedCount, errorCount ); @@ -397,7 +397,7 @@ LIB LoadConfigurationStatus smLoadConfigurationFromBuffer( const smbus smhandle, bool deviceDisabled=false; //parse DRC header - if(parseDRCInfo(drcData,drcDataLength,&DRCVersion,&numParams,&DRCFileFeatureBits,&DRCEssentialFileFeatureBits)!=true) + if(!parseDRCInfo(drcData,drcDataLength,&DRCVersion,&numParams,&DRCFileFeatureBits,&DRCEssentialFileFeatureBits)) return CFGInvalidFile; //check if essential bits have something that is not in feature bits (file sanity check error) @@ -1068,7 +1068,7 @@ FirmwareUploadStatus smFirmwareUpload( const smbus smhandle, const int smaddress //load file to buffer if not loaded yet if(fileLoaded==false) { - if(loadBinaryFile(firmware_filename,&fwData,&fwDataLength,false)!=true) + if(!loadBinaryFile(firmware_filename,&fwData,&fwDataLength,false)) return FWFileNotReadable; fileLoaded=true; } diff --git a/simplemotion.c b/simplemotion.c index 9567dc9..c2c954f 100644 --- a/simplemotion.c +++ b/simplemotion.c @@ -411,30 +411,30 @@ SM_STATUS smSendSMCMD( smbus handle, smuint8 cmdid, smuint8 addr, smuint8 datale smDebug(handle,SMDebugHigh," Outbound packet raw data: CMDID (%d) ",cmdid); - if( smWriteByte(handle,cmdid, &sendcrc) != true ) return recordStatus(handle,SM_ERR_BUS); + if(!smWriteByte(handle,cmdid, &sendcrc)) return recordStatus(handle,SM_ERR_BUS); if(cmdid&SMCMD_MASK_N_PARAMS) { smDebug(DEBUG_PRINT_RAW,SMDebugHigh,"SIZE (%d bytes) ", datalen); - if( smWriteByte(handle,datalen, &sendcrc) != true ) return recordStatus(handle,SM_ERR_BUS); + if(!smWriteByte(handle,datalen, &sendcrc)) return recordStatus(handle,SM_ERR_BUS); } smDebug(DEBUG_PRINT_RAW,SMDebugHigh,"ADDR (%d) ",addr); - if( smWriteByte(handle,addr, &sendcrc) != true ) return recordStatus(handle,SM_ERR_BUS); + if(!smWriteByte(handle,addr, &sendcrc)) return recordStatus(handle,SM_ERR_BUS); smDebug(DEBUG_PRINT_RAW,SMDebugHigh,"PAYLOAD ("); for(i=0;i>8, sendcrc&0xff); - if( smWriteByte(handle,sendcrc>>8, NULL) != true ) return recordStatus(handle,SM_ERR_BUS); - if( smWriteByte(handle,sendcrc&0xff,NULL) != true ) return recordStatus(handle,SM_ERR_BUS); + if(!smWriteByte(handle,sendcrc>>8, NULL)) return recordStatus(handle,SM_ERR_BUS); + if(!smWriteByte(handle,sendcrc&0xff,NULL)) return recordStatus(handle,SM_ERR_BUS); //transmit bytes to bus that were written in buffer by smWriteByte calls - if( smTransmitBuffer(handle) != true ) return recordStatus(handle,SM_ERR_BUS); + if(!smTransmitBuffer(handle)) return recordStatus(handle,SM_ERR_BUS); return recordStatus(handle,SM_OK); } @@ -467,7 +467,7 @@ SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, //send for(i=0;i<7;i++) { - if( smWriteByte(handle,cmd[i], NULL) != true ) + if(!smWriteByte(handle,cmd[i], NULL)) return recordStatus(handle,SM_ERR_BUS); } smTransmitBuffer(handle);//this sends the bytes entered with smWriteByte @@ -479,7 +479,7 @@ SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, smuint8 rx; success=smBDRead(smBus[handle].bdHandle,&rx); cmd[i]=rx; - if(success!=true) + if(!success) { smDebug(handle,SMDebugLow,"Not enough data received on smFastUpdateCycle"); return recordStatus(handle,SM_ERR_BUS|SM_ERR_LENGTH);//no enough data received @@ -608,7 +608,7 @@ SM_STATUS smTransmitReceiveCommandQueue( const smbus bushandle, const smaddr tar //check if bus handle is valid & opened if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); - if(smBus[bushandle].transmitBufFull!=true) //dont send/receive commands if queue was overflowed by user error + if(!smBus[bushandle].transmitBufFull) //dont send/receive commands if queue was overflowed by user error { stat=smSendSMCMD(bushandle,cmdid,targetaddress, smBus[bushandle].cmd_send_queue_bytes, smBus[bushandle].recv_rsbuf ); //send commands to bus if(stat!=SM_OK) return recordStatus(bushandle,stat); @@ -617,7 +617,7 @@ SM_STATUS smTransmitReceiveCommandQueue( const smbus bushandle, const smaddr tar smBus[bushandle].cmd_send_queue_bytes=0; smBus[bushandle].cmd_recv_queue_bytes=0;//counted upwards at every smGetQueued.. and compared to payload size - if(smBus[bushandle].transmitBufFull!=true && targetaddress!=0)//dont send/receive commands if queue was overflowed by user error, or if target is broadcast address (0) where no slave will respond and it's ok + if(!smBus[bushandle].transmitBufFull && targetaddress!=0)//dont send/receive commands if queue was overflowed by user error, or if target is broadcast address (0) where no slave will respond and it's ok { stat=smReceiveReturnPacket(bushandle);//blocking wait & receive return values from bus if(stat!=SM_OK) return recordStatus(bushandle,stat); //maybe timeouted From f25e27c228f7d9f0592824e673dbaa1b374941fb Mon Sep 17 00:00:00 2001 From: Joonas Koivunen Date: Sat, 9 Nov 2019 20:55:48 +0200 Subject: [PATCH 05/11] refactor clean up false comparisons --- bufferedmotion.c | 4 ++-- busdevice.c | 18 +++++++------- devicedeployment.c | 24 +++++++++---------- simplemotion.c | 60 +++++++++++++++++++++++----------------------- 4 files changed, 53 insertions(+), 53 deletions(-) diff --git a/bufferedmotion.c b/bufferedmotion.c index 07d44dc..caaee25 100644 --- a/bufferedmotion.c +++ b/bufferedmotion.c @@ -150,11 +150,11 @@ SM_STATUS smBufferedFillAndReceive(BufferedMotionAxis *axis, smint32 numFillPoin // emit message(Warning,"Buffer underrun on axis "+QString::number(ax)); //freeBytesInDeviceBuffer-=8; -// if(drives[ax].bufferedStreamInitialized==false) +// if(!drives[ax].bufferedStreamInitialized) // cmdBufferSizeBytes=freeBytesInDeviceBuffer;//get empty buffer size //first initialize the stream if not done yet - if(axis->readParamInitialized==false) + if(!axis->readParamInitialized) { //set acceleration to "infinite" to avoid modification of user supplied trajectory inside drive smAppendSMCommandToQueue(axis->bushandle,SMPCMD_SETPARAMADDR,SMP_RETURN_PARAM_ADDR); diff --git a/busdevice.c b/busdevice.c index bfca58c..71d2b4a 100644 --- a/busdevice.c +++ b/busdevice.c @@ -85,13 +85,13 @@ smbusdevicehandle smBDOpenWithCallbacks(const char *devicename, BusdeviceOpen bu bool success; //true on first call - if(bdInitialized==false) + if(!bdInitialized) smBDinit(); //find free handle for(handle=0;handle=SM_MAX_BUSES) return -1; @@ -257,13 +257,13 @@ smbus smOpenBusWithCallbacks( const char *devicename, BusdeviceOpen busOpenCallb int handle; //true on first call - if(smInitialized==false) + if(!smInitialized) smBusesInit(); //find free handle for(handle=0;handle=SM_MAX_BUSES) return -1; @@ -307,11 +307,11 @@ LIB void smSetBaudrate( unsigned long pbs ) LIB SM_STATUS smCloseBus( const smbus bushandle ) { //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); + if(!smIsHandleOpen(bushandle)) return recordStatus(bushandle,SM_ERR_NODEVICE); smBus[bushandle].opened=false; - if( smBDClose(smBus[bushandle].bdHandle) == false ) return recordStatus(bushandle,SM_ERR_BUS); + if(!smBDClose(smBus[bushandle].bdHandle)) return recordStatus(bushandle,SM_ERR_BUS); return SM_OK; } @@ -322,7 +322,7 @@ LIB SM_STATUS smCloseBus( const smbus bushandle ) LIB SM_STATUS smPurge( const smbus bushandle ) { //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); + if(!smIsHandleOpen(bushandle)) return recordStatus(bushandle,SM_ERR_NODEVICE); if(smBDMiscOperation( bushandle, MiscOperationPurgeRX )) return recordStatus(bushandle,SM_OK); @@ -336,7 +336,7 @@ LIB SM_STATUS smPurge( const smbus bushandle ) LIB SM_STATUS smFlushTX( const smbus bushandle ) { //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); + if(!smIsHandleOpen(bushandle)) return recordStatus(bushandle,SM_ERR_NODEVICE); if(smBDMiscOperation( bushandle, MiscOperationFlushTX )) return recordStatus(bushandle,SM_OK); @@ -375,7 +375,7 @@ char *cmdidToStr(smuint8 cmdid ) bool smWriteByte( const smbus handle, const smuint8 byte, smuint16 *crc ) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; bool success=smBDWrite(smBus[handle].bdHandle,byte); if(crc!=NULL) @@ -389,7 +389,7 @@ bool smWriteByte( const smbus handle, const smuint8 byte, smuint16 *crc ) bool smTransmitBuffer( const smbus handle ) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; bool success=smBDTransmit(smBus[handle].bdHandle); return success; @@ -401,7 +401,7 @@ SM_STATUS smSendSMCMD( smbus handle, smuint8 cmdid, smuint8 addr, smuint8 datale smuint16 sendcrc; //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; sendcrc=SM485_CRCINIT; @@ -448,7 +448,7 @@ LIB SM_STATUS smFastUpdateCycleWithStructs( smbus handle, smuint8 nodeAddress, F SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, smuint16 write2, smuint16 *read1, smuint16 *read2) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; smDebug(handle, SMDebugHigh, "> %s (addr=%d, w1=%d, w2=%d)\n",cmdidToStr(SMCMD_FAST_UPDATE_CYCLE), nodeAddress, @@ -511,7 +511,7 @@ SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, SM_STATUS smReceiveErrorHandler( smbus handle, bool flushrx ) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; //empty pending rx buffer to avoid further parse errors @@ -534,7 +534,7 @@ SM_STATUS smAppendSMCommandToQueue( smbus handle, int smpCmdType,smint32 paramva int cmdlength; //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; switch(smpCmdType) { @@ -606,7 +606,7 @@ SM_STATUS smTransmitReceiveCommandQueue( const smbus bushandle, const smaddr tar SM_STATUS stat; //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); + if(!smIsHandleOpen(bushandle)) return recordStatus(bushandle,SM_ERR_NODEVICE); if(!smBus[bushandle].transmitBufFull) //dont send/receive commands if queue was overflowed by user error { @@ -637,7 +637,7 @@ SM_STATUS smTransmitReceiveCommandQueue( const smbus bushandle, const smaddr tar SM_STATUS smExecuteCommandQueue( const smbus bushandle, const smaddr targetaddress ) { //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(bushandle)) return SM_ERR_NODEVICE; return recordStatus(bushandle,smTransmitReceiveCommandQueue(bushandle,targetaddress,SMCMD_INSTANT_CMD)); } @@ -650,7 +650,7 @@ SM_STATUS smUploadCommandQueueToDeviceBuffer( const smbus bushandle, const smadd //return number of how many bytes waiting to be read with smGetQueuedSMCommandReturnValue SM_STATUS smBytesReceived( const smbus bushandle, smint32 *bytesinbuffer ) { - if(smIsHandleOpen(bushandle)==false) return recordStatus(bushandle,SM_ERR_NODEVICE); + if(!smIsHandleOpen(bushandle)) return recordStatus(bushandle,SM_ERR_NODEVICE); smint32 bytes=smBus[bushandle].recv_payloadsize - smBus[bushandle].cmd_recv_queue_bytes;//how many bytes waiting to be read with smGetQueuedSMCommandReturnValue *bytesinbuffer=bytes; @@ -663,7 +663,7 @@ SM_STATUS smGetQueuedSMCommandReturnValue( const smbus bushandle, smint32 *retV smuint8 rxbyte, rettype; //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(bushandle)) return SM_ERR_NODEVICE; //if get called so many times that receive queue buffer is already empty, return error @@ -742,7 +742,7 @@ SM_STATUS smGetQueuedSMCommandReturnValue( const smbus bushandle, smint32 *retV SM_STATUS smReceiveReturnPacket( smbus bushandle ) { //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(bushandle)) return SM_ERR_NODEVICE; smDebug(bushandle, SMDebugHigh, " Reading reply packet\n"); do @@ -752,7 +752,7 @@ SM_STATUS smReceiveReturnPacket( smbus bushandle ) bool succ=smBDRead(smBus[bushandle].bdHandle,&ret); - if(succ==false) + if(!succ) { smReceiveErrorHandler(bushandle,false); return recordStatus(bushandle,SM_ERR_COMMUNICATION); @@ -760,7 +760,7 @@ SM_STATUS smReceiveReturnPacket( smbus bushandle ) stat=smParseReturnData( bushandle, ret ); if(stat!=SM_OK) return recordStatus(bushandle,stat); - } while(smBus[bushandle].receiveComplete==false); //loop until complete packaget has been read + } while(!smBus[bushandle].receiveComplete); //loop until complete packaget has been read //return data read complete smDebug(bushandle,SMDebugHigh, "< %s (id=%d, addr=%d, payload=%d)\n", @@ -786,7 +786,7 @@ LIB void smSetDebugOutput( smVerbosityLevel level, FILE *stream ) SM_STATUS smParseReturnData( smbus handle, smuint8 data ) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; //buffered variable allows placing if's in any order (because recv_state may changes in this function) smBus[handle].recv_state=smBus[handle].recv_state_next; @@ -888,7 +888,7 @@ SM_STATUS smAppendGetParamCommandToQueue( smbus handle, smint16 paramAddress ) SM_STATUS stat=SM_NONE; //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; //possible errors will set bits to stat stat|=smAppendSMCommandToQueue( handle, SMPCMD_SETPARAMADDR, SMP_RETURN_PARAM_LEN ); //2b @@ -906,7 +906,7 @@ SM_STATUS smGetQueuedGetParamReturnValue( const smbus bushandle, smint32 *retVa SM_STATUS stat=SM_NONE; //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(bushandle)) return SM_ERR_NODEVICE; //must get all inserted commands from buffer stat|=smGetQueuedSMCommandReturnValue( bushandle, &retVal );//4x4b @@ -923,7 +923,7 @@ SM_STATUS smAppendSetParamCommandToQueue( smbus handle, smint16 paramAddress, sm SM_STATUS stat=SM_NONE; //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; stat|=smAppendSMCommandToQueue( handle, SMPCMD_SETPARAMADDR, paramAddress );//2b stat|=smAppendSMCommandToQueue( handle, SMPCMD_32B, paramValue );//4b @@ -937,7 +937,7 @@ SM_STATUS smGetQueuedSetParamReturnValue( const smbus bushandle, smint32 *retVa SM_STATUS stat=SM_NONE; //check if bus handle is valid & opened - if(smIsHandleOpen(bushandle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(bushandle)) return SM_ERR_NODEVICE; //must get all inserted commands from buffer stat|=smGetQueuedSMCommandReturnValue( bushandle, &retVal ); @@ -955,7 +955,7 @@ SM_STATUS smGetBufferClock( const smbus handle, const smaddr targetaddr, smuint1 smDebug(handle,SMDebugMid,"smGetBufferClock: target SM address %d.\n",(int)targetaddr); //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==false) return recordStatus(handle,SM_ERR_NODEVICE); + if(!smIsHandleOpen(handle)) return recordStatus(handle,SM_ERR_NODEVICE); stat=smSendSMCMD(handle, SMCMD_GET_CLOCK ,targetaddr, 0, NULL ); //send get clock commands to bus if(stat!=SM_OK) return recordStatus(handle,stat); @@ -1056,7 +1056,7 @@ SM_STATUS smSetParameter( const smbus handle, const smaddr nodeAddress, const sm SM_STATUS recordStatus( const smbus handle, const SM_STATUS stat ) { //check if bus handle is valid & opened - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; if(smBus[handle].cumulativeSmStatus!=stat && stat!=SM_OK)//if status changed and new status is not SM_OK smDebug(handle,SMDebugLow,"Previous SM call failed and changed the SM_STATUS value obtainable with getCumulativeStatus(). Status before failure was %d, and new error flag valued %d has been now set.\n",(int)smBus[handle].cumulativeSmStatus,(int)stat); @@ -1070,7 +1070,7 @@ SM_STATUS recordStatus( const smbus handle, const SM_STATUS stat ) /** This function returns all occurred SM_STATUS bits after smOpenBus or resetCumulativeStatus call*/ SM_STATUS getCumulativeStatus( const smbus handle ) { - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; return smBus[handle].cumulativeSmStatus; } @@ -1078,7 +1078,7 @@ SM_STATUS getCumulativeStatus( const smbus handle ) /** Reset cululative status so getCumultiveStatus returns 0 after calling this until one of the other functions are called*/ SM_STATUS resetCumulativeStatus( const smbus handle ) { - if(smIsHandleOpen(handle)==false) return SM_ERR_NODEVICE; + if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; smDebug(handle,SMDebugMid,"resetCumulativeStatus called.\n"); From 9087e126b1440e69e61aa4b2d7dc80466087df50 Mon Sep 17 00:00:00 2001 From: Joonas Koivunen Date: Sat, 9 Nov 2019 21:02:51 +0200 Subject: [PATCH 06/11] refactor use standard numeric types --- bufferedmotion.c | 16 ++--- bufferedmotion.h | 38 +++++------ busdevice.c | 12 ++-- busdevice.h | 10 +-- devicedeployment.c | 144 ++++++++++++++++++++--------------------- devicedeployment.h | 6 +- simplemotion.c | 140 +++++++++++++++++++-------------------- simplemotion.h | 46 ++++++------- simplemotion_defs.h | 10 +-- simplemotion_private.h | 16 ++--- simplemotion_types.h | 86 ++++++++++++------------ sm_consts.c | 6 +- 12 files changed, 265 insertions(+), 265 deletions(-) diff --git a/bufferedmotion.c b/bufferedmotion.c index caaee25..5eafcca 100644 --- a/bufferedmotion.c +++ b/bufferedmotion.c @@ -5,7 +5,7 @@ #include "sm485.h" /** initialize buffered motion for one axis with address and samplerate (Hz) */ -SM_STATUS smBufferedInit(BufferedMotionAxis *newAxis, smbus handle, smaddr deviceAddress, smint32 sampleRate, smint16 readParamAddr, smuint8 readDataLength ) +SM_STATUS smBufferedInit(BufferedMotionAxis *newAxis, smbus handle, smaddr deviceAddress, int32_t sampleRate, int16_t readParamAddr, uint8_t readDataLength ) { //value out of range if(sampleRate<1 || sampleRate>2500) @@ -99,9 +99,9 @@ SM_STATUS smBufferedRunAndSyncClocks(BufferedMotionAxis *axis) return smGetBufferClock( axis->bushandle, axis->deviceAddress, &axis->driveClock ); } -SM_STATUS smBufferedGetFree(BufferedMotionAxis *axis, smint32 *numBytesFree ) +SM_STATUS smBufferedGetFree(BufferedMotionAxis *axis, int32_t *numBytesFree ) { - smint32 freebytes; + int32_t freebytes; if(smRead1Parameter(axis->bushandle,axis->deviceAddress,SMP_BUFFER_FREE_BYTES,&freebytes)!=SM_OK) { @@ -117,7 +117,7 @@ SM_STATUS smBufferedGetFree(BufferedMotionAxis *axis, smint32 *numBytesFree ) return getCumulativeStatus(axis->bushandle); } -smint32 smBufferedGetMaxFillSize(BufferedMotionAxis *axis, smint32 numBytesFree ) +int32_t smBufferedGetMaxFillSize(BufferedMotionAxis *axis, int32_t numBytesFree ) { //even if we have lots of free space in buffer, we can only send up to SM485_MAX_PAYLOAD_BYTES bytes at once in one SM transmission if(numBytesFree>SM485_MAX_PAYLOAD_BYTES) @@ -132,7 +132,7 @@ smint32 smBufferedGetMaxFillSize(BufferedMotionAxis *axis, smint32 numBytesFree return (numBytesFree-2-3-2-3-2)/4;//if read data uninitialized, it takes extra n bytes to init on next fill, so reduce it here } -smint32 smBufferedGetBytesConsumed(BufferedMotionAxis *axis, smint32 numFillPoints ) +int32_t smBufferedGetBytesConsumed(BufferedMotionAxis *axis, int32_t numFillPoints ) { //calculate number of bytes that the number of fill points will consume from buffer if(axis->readParamInitialized) @@ -142,9 +142,9 @@ smint32 smBufferedGetBytesConsumed(BufferedMotionAxis *axis, smint32 numFillPoin } -SM_STATUS smBufferedFillAndReceive(BufferedMotionAxis *axis, smint32 numFillPoints, smint32 *fillPoints, smint32 *numReceivedPoints, smint32 *receivedPoints, smint32 *bytesFilled ) +SM_STATUS smBufferedFillAndReceive(BufferedMotionAxis *axis, int32_t numFillPoints, int32_t *fillPoints, int32_t *numReceivedPoints, int32_t *receivedPoints, int32_t *bytesFilled ) { - smint32 bytesUsed=0; + int32_t bytesUsed=0; //if(freeBytesInDeviceBuffer>=cmdBufferSizeBytes) // emit message(Warning,"Buffer underrun on axis "+QString::number(ax)); @@ -199,7 +199,7 @@ SM_STATUS smBufferedFillAndReceive(BufferedMotionAxis *axis, smint32 numFillPoin //read all available return data from stream (commands that have been axecuted in drive so far) //return data works like FIFO for all sent commands (each sent stream command will produce return data packet that we fetch here) { - smint32 bufferedReturnBytesReceived,readval; + int32_t bufferedReturnBytesReceived,readval; int n=0; //read return data buffer diff --git a/bufferedmotion.h b/bufferedmotion.h index dd0e32b..bb31bd2 100644 --- a/bufferedmotion.h +++ b/bufferedmotion.h @@ -12,23 +12,23 @@ extern "C"{ typedef struct _BufferedMotionAxis { bool initialized; bool readParamInitialized; - smint32 numberOfDiscardableReturnDataPackets; - smint32 numberOfPendingReadPackets;//number of read data packets that should be arriving from device (to read rest of pending data, use smBufferedFillAndReceive(numFillPoints=0) until this variable this goes to zero) + int32_t numberOfDiscardableReturnDataPackets; + int32_t numberOfPendingReadPackets;//number of read data packets that should be arriving from device (to read rest of pending data, use smBufferedFillAndReceive(numFillPoints=0) until this variable this goes to zero) smbus bushandle; smaddr deviceAddress; - smint32 samplerate; - smint16 readParamAddr; - smuint8 readParamLength; - smint32 driveFlagsBeforeInit; + int32_t samplerate; + int16_t readParamAddr; + uint8_t readParamLength; + int32_t driveFlagsBeforeInit; bool driveFlagsModifiedAtInit;//true if deInit should restore driveFlagsBeforeInit - smint32 driveAccelerationBeforeInit; - smuint16 driveClock;//clock counter is updated at smBufferedRunAndSyncClocks only for the one axis that is used with that func. clock is running up at 10kHz count rate, meaning that it rolls over every 6.5536 secs - smint32 bufferLength;//buffer lenght in bytes of the device. note this may be different in different devices types. so call smBufferedGetFree on the device that has the smallest buffer. however as of 2.2016 all GD drives have 2048 bytes buffers. - smint32 bufferFreeBytes;//number of bytes free in buffer, updated at smBufferedGetFree - smint32 bufferFill;//percentage of buffer fill, updated at smBufferedGetFree. this should stay above 50% to ensure gapless motion. if gaps occur, check SMV2USB adpater COM port latency setting (set to 1ms) or try lower samplerate. - smint32 smProtocolVersion;//version of SM protocol of the target device. some internal functionality of API may use this info. - smint32 deviceCapabilityFlags1;//value of SMP_DEVICE_CAPABILITIES1 if target device has SM protocol version 28 or later (if SM version<28, then value is 0) - smint32 deviceCapabilityFlags2;//value of SMP_DEVICE_CAPABILITIES2 if target device has SM protocol version 28 or later (if SM version<28, then value is 0) + int32_t driveAccelerationBeforeInit; + uint16_t driveClock;//clock counter is updated at smBufferedRunAndSyncClocks only for the one axis that is used with that func. clock is running up at 10kHz count rate, meaning that it rolls over every 6.5536 secs + int32_t bufferLength;//buffer lenght in bytes of the device. note this may be different in different devices types. so call smBufferedGetFree on the device that has the smallest buffer. however as of 2.2016 all GD drives have 2048 bytes buffers. + int32_t bufferFreeBytes;//number of bytes free in buffer, updated at smBufferedGetFree + int32_t bufferFill;//percentage of buffer fill, updated at smBufferedGetFree. this should stay above 50% to ensure gapless motion. if gaps occur, check SMV2USB adpater COM port latency setting (set to 1ms) or try lower samplerate. + int32_t smProtocolVersion;//version of SM protocol of the target device. some internal functionality of API may use this info. + int32_t deviceCapabilityFlags1;//value of SMP_DEVICE_CAPABILITIES1 if target device has SM protocol version 28 or later (if SM version<28, then value is 0) + int32_t deviceCapabilityFlags2;//value of SMP_DEVICE_CAPABILITIES2 if target device has SM protocol version 28 or later (if SM version<28, then value is 0) } BufferedMotionAxis; /** initialize buffered motion for one axis with address and samplerate (Hz) */ @@ -47,17 +47,17 @@ typedef struct _BufferedMotionAxis { Note return data per one FillAndReceive must not exceed 120 bytes. So max allowed numFillPoints will depend on returnDataLength. numFillPoints must be equal or below 30 for 32B, 40 for 24B and 60 for 16B. */ -LIB SM_STATUS smBufferedInit( BufferedMotionAxis *newAxis, smbus handle, smaddr deviceAddress, smint32 sampleRate, smint16 readParamAddr, smuint8 readDataLength ); +LIB SM_STATUS smBufferedInit( BufferedMotionAxis *newAxis, smbus handle, smaddr deviceAddress, int32_t sampleRate, int16_t readParamAddr, uint8_t readDataLength ); /** uninitialize axis from buffered motion, recommended to call this before closing bus so drive's adjusted parameters are restored to originals*/ LIB SM_STATUS smBufferedDeinit( BufferedMotionAxis *axis ); /* this also starts buffered motion when it's not running*/ LIB SM_STATUS smBufferedRunAndSyncClocks( BufferedMotionAxis *axis ); -LIB SM_STATUS smBufferedGetFree(BufferedMotionAxis *axis, smint32 *numBytesFree ); -LIB smint32 smBufferedGetMaxFillSize(BufferedMotionAxis *axis, smint32 numBytesFree ); -LIB smint32 smBufferedGetBytesConsumed(BufferedMotionAxis *axis, smint32 numFillPoints ); -LIB SM_STATUS smBufferedFillAndReceive( BufferedMotionAxis *axis, smint32 numFillPoints, smint32 *fillPoints, smint32 *numReceivedPoints, smint32 *receivedPoints, smint32 *bytesFilled ); +LIB SM_STATUS smBufferedGetFree(BufferedMotionAxis *axis, int32_t *numBytesFree ); +LIB int32_t smBufferedGetMaxFillSize(BufferedMotionAxis *axis, int32_t numBytesFree ); +LIB int32_t smBufferedGetBytesConsumed(BufferedMotionAxis *axis, int32_t numFillPoints ); +LIB SM_STATUS smBufferedFillAndReceive( BufferedMotionAxis *axis, int32_t numFillPoints, int32_t *fillPoints, int32_t *numReceivedPoints, int32_t *receivedPoints, int32_t *bytesFilled ); /** This will stop executing buffered motion immediately and discard rest of already filled buffer on a given axis. May cause drive fault state such as tracking error if done at high speed because stop happens without deceleration. Note: this will not stop motion, but just stop executing the sent buffered commands. The last executed motion point will be still followed by drive. So this is bad function for quick stopping stopping, for stop to the actual place consider using disable drive instead (prefferably phsyical input disable). diff --git a/busdevice.c b/busdevice.c index 71d2b4a..7f688a0 100644 --- a/busdevice.c +++ b/busdevice.c @@ -25,8 +25,8 @@ typedef struct _SMBusDevice //pointer used by bus device drivers smBusdevicePointer busDevicePointer; - smuint8 txBuffer[TANSMIT_BUFFER_LENGTH]; - smint32 txBufferUsed;//how many bytes in buffer currently + uint8_t txBuffer[TANSMIT_BUFFER_LENGTH]; + int32_t txBufferUsed;//how many bytes in buffer currently BusdeviceOpen busOpenCallback; BusdeviceReadBuffer busReadCallback; @@ -149,7 +149,7 @@ bool smBDClose( const smbusdevicehandle handle ) //write one byte to buffer and send later with smBDTransmit() //returns true on success -bool smBDWrite(const smbusdevicehandle handle, const smuint8 byte ) +bool smBDWrite(const smbusdevicehandle handle, const uint8_t byte ) { //check if handle valid & open if(!smIsBDHandleOpen(handle)) return false; @@ -186,7 +186,7 @@ bool smBDTransmit(const smbusdevicehandle handle) //read one byte from bus. if byte not immediately available, block return up to SM_READ_TIMEOUT millisecs to wait data //returns true if byte read sucessfully -bool smBDRead( const smbusdevicehandle handle, smuint8 *byte ) +bool smBDRead( const smbusdevicehandle handle, uint8_t *byte ) { //check if handle valid & open if(!smIsBDHandleOpen(handle)) return false; @@ -220,7 +220,7 @@ bool smBDMiscOperation(const smbusdevicehandle handle , BusDeviceMiscOperationTy //BUS DEVICE INFO FETCH FUNCTIONS: //Return number of bus devices found. details of each device may be consequently fetched by smGetBusDeviceDetails() -smint smBDGetNumberOfDetectedBuses() +int smBDGetNumberOfDetectedBuses() { //only supports FTDI D2XX at the moment #ifdef FTDI_D2XX_SUPPORT @@ -229,7 +229,7 @@ smint smBDGetNumberOfDetectedBuses() return 0; } -bool smBDGetBusDeviceDetails( smint index, SM_BUS_DEVICE_INFO *info ) +bool smBDGetBusDeviceDetails( int index, SM_BUS_DEVICE_INFO *info ) { //only supports FTDI D2XX at the moment #ifdef FTDI_D2XX_SUPPORT diff --git a/busdevice.h b/busdevice.h index 1726032..073e300 100644 --- a/busdevice.h +++ b/busdevice.h @@ -6,7 +6,7 @@ #include "simplemotion.h" #include "simplemotion_private.h" -typedef smint16 smbusdevicehandle; +typedef int16_t smbusdevicehandle; #define SM_BAUDRATE 460800 @@ -21,7 +21,7 @@ bool smBDClose( const smbusdevicehandle handle ); //write one byte to trasmit buffer. send data with smBDTransmit() //returns true on success. false could mean buffer full error if forgot to call smBDTransmit -bool smBDWrite( const smbusdevicehandle handle , const smuint8 byte ); +bool smBDWrite( const smbusdevicehandle handle , const uint8_t byte ); //write transmit buffer to physical device //returns true on success @@ -29,7 +29,7 @@ bool smBDTransmit(const smbusdevicehandle handle); //read one byte from bus. if byte not immediately available, block return up to SM_READ_TIMEOUT millisecs to wait data //returns true if byte read sucessfully -bool smBDRead( const smbusdevicehandle handle , smuint8 *byte ); +bool smBDRead( const smbusdevicehandle handle , uint8_t *byte ); //see info at definition of BusDeviceMiscOperationType //returns true if sucessfully @@ -38,10 +38,10 @@ bool smBDMiscOperation( const smbusdevicehandle handle, BusDeviceMiscOperationTy //BUS DEVICE INFO FETCH FUNCTIONS: // Return number of bus devices found. details of each device may be consequently fetched by smBDGetBusDeviceDetails() -smint smBDGetNumberOfDetectedBuses(); +int smBDGetNumberOfDetectedBuses(); //return true if success -bool smBDGetBusDeviceDetails( smint index, SM_BUS_DEVICE_INFO *info ); +bool smBDGetBusDeviceDetails( int index, SM_BUS_DEVICE_INFO *info ); #endif diff --git a/devicedeployment.c b/devicedeployment.c index 58096df..14250d1 100755 --- a/devicedeployment.c +++ b/devicedeployment.c @@ -39,7 +39,7 @@ int globalErrorDetailCode=0; -bool loadBinaryFile( const char *filename, smuint8 **data, int *numbytes, bool addNullTermination ); +bool loadBinaryFile( const char *filename, uint8_t **data, int *numbytes, bool addNullTermination ); int smGetDeploymentToolErrroDetail() { @@ -48,7 +48,7 @@ int smGetDeploymentToolErrroDetail() //return -1 if EOF //readPosition should be initialized to 0 and not touched by caller after that. this func will increment it after each call. -unsigned int readFileLine( const smuint8 *data, const int dataLen, int *readPosition, int charlimit, char *output, bool *eof) +unsigned int readFileLine( const uint8_t *data, const int dataLen, int *readPosition, int charlimit, char *output, bool *eof) { int len=0; char c; @@ -91,7 +91,7 @@ typedef struct #define maxLineLen 100 //returns byte offset where str starts, or -1 if not found before data ends -int findSubstring( const smuint8 *data, const int dataLen, const char *str ) +int findSubstring( const uint8_t *data, const int dataLen, const char *str ) { int strLen=strlen(str); int i; @@ -226,7 +226,7 @@ int stringToInt( const char *str, int *output ) return 1; } -bool parseDRCIntKey( const smuint8 *drcData, const int drcDataLen, const char *key, int *outValue ) +bool parseDRCIntKey( const uint8_t *drcData, const int drcDataLen, const char *key, int *outValue ) { int pos=findSubstring(drcData,drcDataLen,key); if(pos<0) @@ -239,7 +239,7 @@ bool parseDRCIntKey( const smuint8 *drcData, const int drcDataLen, const char *k } //read DRC file version nr and nubmer of params it contains. if succes, returns true. if invalid file, return false -bool parseDRCInfo( const smuint8 *drcData, const int drcDataLen, int *DRCVersion, int *numParams, int *DRCFileFeatureBits, int *DRCEssentialFileFeatureBits ) +bool parseDRCInfo( const uint8_t *drcData, const int drcDataLen, int *DRCVersion, int *numParams, int *DRCFileFeatureBits, int *DRCEssentialFileFeatureBits ) { const char *DRCFileFeatureBitsKey="FileFeatureBits="; const char *DRCEssentialFileFeatureBitsKey="FileFeatureBitsEssential="; @@ -270,7 +270,7 @@ bool parseDRCInfo( const smuint8 *drcData, const int drcDataLen, int *DRCVersion return true; } -bool parseParameter( const smuint8 *drcData, const int drcDataLen, int idx, Parameter *param ) +bool parseParameter( const uint8_t *drcData, const int drcDataLen, int idx, Parameter *param ) { char line[maxLineLen]; char scanline[maxLineLen]; @@ -356,7 +356,7 @@ bool parseParameter( const smuint8 *drcData, const int drcDataLen, int idx, Para LoadConfigurationStatus smLoadConfiguration(const smbus smhandle, const int smaddress, const char *filename, unsigned int mode , int *skippedCount, int *errorCount) { LoadConfigurationStatus ret; - smuint8 *drcData=NULL; + uint8_t *drcData=NULL; int drcDataLength; if(!loadBinaryFile(filename,&drcData,&drcDataLength,true)) @@ -379,16 +379,16 @@ LoadConfigurationStatus smLoadConfiguration(const smbus smhandle, const int smad * * Requires DRC file version 111 or later to use CONFIGMODE_REQUIRE_SAME_FW. */ -LIB LoadConfigurationStatus smLoadConfigurationFromBuffer( const smbus smhandle, const int smaddress, const smuint8 *drcData, const int drcDataLength, unsigned int mode, int *skippedCount, int *errorCount ) +LIB LoadConfigurationStatus smLoadConfigurationFromBuffer( const smbus smhandle, const int smaddress, const uint8_t *drcData, const int drcDataLength, unsigned int mode, int *skippedCount, int *errorCount ) { smDebug(smhandle,SMDebugLow,"smLoadConfigurationFromBuffer for SM address %d called\n",smaddress); //test connection - smint32 devicetype; + int32_t devicetype; SM_STATUS stat; int ignoredCount=0; int setErrors=0; - smint32 CB1Value; + int32_t CB1Value; int changed=0; int numParams, DRCVersion; int DRCFileFeatureBits, DRCEssentialFileFeatureBits; @@ -443,7 +443,7 @@ LIB LoadConfigurationStatus smLoadConfigurationFromBuffer( const smbus smhandle, if(!param.readOnly) { - smint32 currentValue; + int32_t currentValue; int configFileValue=round(param.value*param.scale-param.offset); @@ -467,9 +467,9 @@ LIB LoadConfigurationStatus smLoadConfigurationFromBuffer( const smbus smhandle, } resetCumulativeStatus( smhandle ); - smint32 dummy; - smint32 cmdSetAddressStatus; - smint32 cmdSetValueStatus; + int32_t dummy; + int32_t cmdSetAddressStatus; + int32_t cmdSetValueStatus; smDebug(smhandle,SMDebugMid,"Writing parameter addr %d value %d\n",param.address,configFileValue); //use low level SM commands so we can get execution status of each subpacet: @@ -535,7 +535,7 @@ LIB LoadConfigurationStatus smLoadConfigurationFromBuffer( const smbus smhandle, smSetParameter( smhandle, smaddress, SMP_CONTROL_BITS1, CB1Value );//restore controbits1 (enable if it was enabled before) } - smint32 statusbits; + int32_t statusbits; smRead1Parameter( smhandle, smaddress, SMP_STATUS, &statusbits ); //restart drive if necessary or if forced @@ -567,17 +567,17 @@ LIB LoadConfigurationStatus smLoadConfigurationFromBuffer( const smbus smhandle, * @param UID result will be written to this pointer * @return true if success, false if failed (if communication otherwise works, then probably UID feature not present in this firmware version). Note: some devices' DFU/bootloader mode don't support this command but main firmware do. */ -bool smGetDeviceFirmwareUniqueID( smbus smhandle, int deviceaddress, smuint32 *UID ) +bool smGetDeviceFirmwareUniqueID( smbus smhandle, int deviceaddress, uint32_t *UID ) { smDebug(smhandle,SMDebugMid,"smGetDeviceFirmwareUniqueID called\n"); - smint32 fwBinaryChecksum, commandStatus; + int32_t fwBinaryChecksum, commandStatus; resetCumulativeStatus(smhandle); smSetParameter( smhandle, deviceaddress, SMP_CUMULATIVE_STATUS, 0);//reset any SM access error that might SM target might have active so we can test whether following command succeeds smSetParameter( smhandle, deviceaddress, SMP_SYSTEM_CONTROL, SMP_SYSTEM_CONTROL_GET_SPECIAL_DATA); smRead2Parameters( smhandle, deviceaddress, SMP_DEBUGPARAM1, &fwBinaryChecksum, SMP_CUMULATIVE_STATUS, &commandStatus ); - *UID=(smuint32) fwBinaryChecksum; + *UID=(uint32_t) fwBinaryChecksum; if(getCumulativeStatus(smhandle)==SM_OK && commandStatus==SMP_CMD_STATUS_ACK)//if commandStatus==SMP_CMD_STATUS_ACK fails, then FW or curren mode of device doesn't support reading this return true; @@ -593,26 +593,26 @@ bool smGetDeviceFirmwareUniqueID( smbus smhandle, int deviceaddress, smuint32 *U */ -smuint8 bufferGet8( smuint8 **buf ) +uint8_t bufferGet8( uint8_t **buf ) { - smuint8 ret=(*buf)[0]; + uint8_t ret=(*buf)[0]; *buf++; return ret; } -smuint16 bufferGet16( smuint8 **buf ) +uint16_t bufferGet16( uint8_t **buf ) { UnionOf4Bytes d; d.U8[0]=(*buf)[0]; d.U8[1]=(*buf)[1]; - smuint16 ret=d.U16[0]; + uint16_t ret=d.U16[0]; *buf+=2; return ret; } -smuint32 bufferGet32( smuint8 **buf ) +uint32_t bufferGet32( uint8_t **buf ) { UnionOf4Bytes d; d.U8[0]=(*buf)[0]; @@ -620,39 +620,39 @@ smuint32 bufferGet32( smuint8 **buf ) d.U8[2]=(*buf)[2]; d.U8[3]=(*buf)[3]; - smuint32 ret=d.U32; + uint32_t ret=d.U32; *buf+=4; return ret; } -FirmwareUploadStatus parseFirmwareFile(smuint8 *data, smuint32 numbytes, smuint32 connectedDeviceTypeId, - smuint32 *primaryMCUDataOffset, smuint32 *primaryMCUDataLenth, - smuint32 *secondaryMCUDataOffset,smuint32 *secondaryMCUDataLength, - smuint32 *FWUniqueID ) +FirmwareUploadStatus parseFirmwareFile(uint8_t *data, uint32_t numbytes, uint32_t connectedDeviceTypeId, + uint32_t *primaryMCUDataOffset, uint32_t *primaryMCUDataLenth, + uint32_t *secondaryMCUDataOffset,uint32_t *secondaryMCUDataLength, + uint32_t *FWUniqueID ) { smDebug(-1,SMDebugMid,"parseFirmwareFile called\n"); //see https://granitedevices.com/wiki/Firmware_file_format_(.gdf) - smuint32 filetype; - filetype=((smuint32*)data)[0]; + uint32_t filetype; + filetype=((uint32_t*)data)[0]; if(filetype!=0x57464447) //check header string "GDFW" return FWInvalidFile; - smuint32 filever, deviceid; + uint32_t filever, deviceid; *FWUniqueID=0;//updated later if available - filever=((smuint16*)data)[2]; + filever=((uint16_t*)data)[2]; if(filever==300)//handle GDF version 300 here { - smuint32 primaryMCUSize, secondaryMCUSize; + uint32_t primaryMCUSize, secondaryMCUSize; - deviceid=((smuint16*)data)[3]; - primaryMCUSize=((smuint32*)data)[2]; - secondaryMCUSize=((smuint32*)data)[3]; + deviceid=((uint16_t*)data)[3]; + primaryMCUSize=((uint32_t*)data)[2]; + secondaryMCUSize=((uint32_t*)data)[3]; if(secondaryMCUSize==0xffffffff) secondaryMCUSize=0;//it is not present @@ -660,12 +660,12 @@ FirmwareUploadStatus parseFirmwareFile(smuint8 *data, smuint32 numbytes, smuint3 return FWIncompatibleFW; //get checksum and check it - smuint32 cksum,cksumcalc=0; - smuint32 i; - smuint32 cksumOffset=4+2+2+4+4+primaryMCUSize+secondaryMCUSize; + uint32_t cksum,cksumcalc=0; + uint32_t i; + uint32_t cksumOffset=4+2+2+4+4+primaryMCUSize+secondaryMCUSize; if(cksumOffset>numbytes-4) return FWInvalidFile; - cksum=((smuint32*)(data+cksumOffset))[0]; + cksum=((uint32_t*)(data+cksumOffset))[0]; for(i=0;i< numbytes-4;i++) { @@ -742,15 +742,15 @@ FirmwareUploadStatus parseFirmwareFile(smuint8 *data, smuint32 numbytes, smuint3 * bits 1-31: reserved * */ - smuint8 *dataPtr=&data[6];//start at byte 6 because first 6 bytes are already read - smuint8 *dataCRCPtr=&data[numbytes-4]; - smuint32 numOfChunks; - smuint32 deviceid_max; - smuint32 chunkType; - smuint32 chunkTypeStringLen; - smuint32 chunkSize; - smuint16 chunkOptions; - smuint32 i; + uint8_t *dataPtr=&data[6];//start at byte 6 because first 6 bytes are already read + uint8_t *dataCRCPtr=&data[numbytes-4]; + uint32_t numOfChunks; + uint32_t deviceid_max; + uint32_t chunkType; + uint32_t chunkTypeStringLen; + uint32_t chunkSize; + uint16_t chunkOptions; + uint32_t i; //check file compatibility if(bufferGet16(&dataPtr)!=400) @@ -789,13 +789,13 @@ FirmwareUploadStatus parseFirmwareFile(smuint8 *data, smuint32 numbytes, smuint3 } else if(chunkType==100)//main MCU FW { - *primaryMCUDataOffset=(smuint32)(dataPtr-data); + *primaryMCUDataOffset=(uint32_t)(dataPtr-data); *primaryMCUDataLenth=chunkSize; dataPtr+=chunkSize;//skip to next chunk } else if(chunkType==200)//secondary MCU FW { - *secondaryMCUDataOffset=(smuint32)(dataPtr-data); + *secondaryMCUDataOffset=(uint32_t)(dataPtr-data); *secondaryMCUDataLength=chunkSize; dataPtr+=chunkSize;//skip to next chunk } @@ -813,7 +813,7 @@ FirmwareUploadStatus parseFirmwareFile(smuint8 *data, smuint32 numbytes, smuint3 } } - if((smuint32)(dataPtr-data)!=numbytes-4)//check if chunks total size match file size + if((uint32_t)(dataPtr-data)!=numbytes-4)//check if chunks total size match file size return FWInvalidFile; } else @@ -851,7 +851,7 @@ void smFirmwareUploadStatusToString(const FirmwareUploadStatus FWUploadStatus, c } -bool loadBinaryFile(const char *filename, smuint8 **data, int *numbytes , bool addNullTermination) +bool loadBinaryFile(const char *filename, uint8_t **data, int *numbytes , bool addNullTermination) { FILE *f; f=fopen(filename,"rb"); @@ -897,10 +897,10 @@ bool loadBinaryFile(const char *filename, smuint8 **data, int *numbytes , bool a //flashing STM32 (host side mcu) -bool flashFirmwarePrimaryMCU( smbus smhandle, int deviceaddress, const smuint8 *data, smint32 size, int *progress ) +bool flashFirmwarePrimaryMCU( smbus smhandle, int deviceaddress, const uint8_t *data, int32_t size, int *progress ) { - smint32 ret; - static smint32 deviceType, fwVersion; + int32_t ret; + static int32_t deviceType, fwVersion; static int uploadIndex; int c; const int BL_CHUNK_LEN=32; @@ -954,12 +954,12 @@ bool flashFirmwarePrimaryMCU( smbus smhandle, int deviceaddress, const smuint8 * smAppendSMCommandToQueue( smhandle, SMPCMD_SETPARAMADDR, SMP_BOOTLOADER_UPLOAD ); for(c=0;c=size) upword=0xeeee; else - upword=((smuint16*)data)[uploadIndex]; + upword=((uint16_t*)data)[uploadIndex]; smAppendSMCommandToQueue( smhandle, SMPCMD_24B, upword ); uploadIndex++; } @@ -1003,9 +1003,9 @@ bool flashFirmwarePrimaryMCU( smbus smhandle, int deviceaddress, const smuint8 * if(fwVersion>=1210) { smSetParameter(smhandle,deviceaddress,SMP_BOOTLOADER_FUNCTION,3);//BL func 3 = verify STM32 FW integrity - smint32 faults; - smint32 loc1; - smint32 loc2; + int32_t faults; + int32_t loc1; + int32_t loc2; smRead3Parameters(smhandle, deviceaddress, SMP_FAULTS, &faults, SMP_FAULT_LOCATION1, &loc1, SMP_FAULT_LOCATION2, &loc2); if(getCumulativeStatus(smhandle)!=SM_OK) @@ -1060,7 +1060,7 @@ FirmwareUploadStatus abortFWUpload( FirmwareUploadStatus stat, UploadState *stat */ FirmwareUploadStatus smFirmwareUpload( const smbus smhandle, const int smaddress, const char *firmware_filename ) { - static smuint8 *fwData=NULL; + static uint8_t *fwData=NULL; static int fwDataLength; static bool fileLoaded=false; FirmwareUploadStatus state; @@ -1095,12 +1095,12 @@ FirmwareUploadStatus smFirmwareUpload( const smbus smhandle, const int smaddress * @param fwDataLenght number of bytes in fwData * @return Enum FirmwareUploadStatus that indicates errors or Complete status. Typecast to integer to get progress value 0-100. */ -FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int smaddress, smuint8 *fwData, const int fwDataLength ) +FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int smaddress, uint8_t *fwData, const int fwDataLength ) { - static smuint32 primaryMCUDataOffset, primaryMCUDataLenth; - static smuint32 secondaryMCUDataOffset,secondaryMCUDataLength; + static uint32_t primaryMCUDataOffset, primaryMCUDataLenth; + static uint32_t secondaryMCUDataOffset,secondaryMCUDataLength; static UploadState state=StatIdle;//state machine status - static smint32 deviceType=0; + static int32_t deviceType=0; static int DFUAddress; static int progress=0; static bool FW_already_installed=false; @@ -1123,7 +1123,7 @@ FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int smDebug(smhandle,SMDebugLow,"smFirmwareUploadFromBuffer: target device type of %d successfully read\n",deviceType); - smuint32 GDFFileUID; + uint32_t GDFFileUID; FirmwareUploadStatus stat=parseFirmwareFile(fwData, fwDataLength, deviceType, &primaryMCUDataOffset, &primaryMCUDataLenth, &secondaryMCUDataOffset, &secondaryMCUDataLength, @@ -1142,7 +1142,7 @@ FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int //check if that FW is already installed if(GDFFileUID!=0)//check only if GDF has provided this value { - smuint32 targetFWUID; + uint32_t targetFWUID; if(smGetDeviceFirmwareUniqueID( smhandle, smaddress, &targetFWUID )) { //reset two upper bits because reading SMP will sign-extend them from 30 bits assuming so that we're reading signed 30 bit integer. @@ -1155,7 +1155,7 @@ FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int smDebug(smhandle,SMDebugLow,"smFirmwareUploadFromBuffer: Same FW is already installed, skipping install\n"); //check if device is in NORMAL mode already - smint32 busMode; + int32_t busMode; stat=smRead1Parameter(smhandle,smaddress,SMP_BUS_MODE,&busMode); if(stat==SM_OK && busMode==SMP_BUS_MODE_NORMAL) { @@ -1182,7 +1182,7 @@ FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int smDebug(smhandle,SMDebugLow,"smFirmwareUploadFromBuffer: StatFirstConnectAttempt\n"); //check if device is in DFU mode already - smint32 busMode; + int32_t busMode; stat=smRead2Parameters(smhandle,smaddress,SMP_BUS_MODE,&busMode, SMP_DEVICE_TYPE, &deviceType); if(stat==SM_OK && busMode==SMP_BUS_MODE_DFU) { @@ -1219,7 +1219,7 @@ FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int smPurge(smhandle); //check if device is in DFU mode already - smint32 busMode; + int32_t busMode; stat=smRead2Parameters(smhandle,smaddress, SMP_BUS_MODE,&busMode, SMP_DEVICE_TYPE, &deviceType); if(stat==SM_OK && busMode==SMP_BUS_MODE_DFU)//is DFU mode { @@ -1245,7 +1245,7 @@ FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int //scan thru addresses where SM device may appear in DFU mode if not appearing in it's original address for(i=245;i<=255;i++) { - smint32 busMode; + int32_t busMode; stat=smRead2Parameters(smhandle,i, SMP_BUS_MODE,&busMode, SMP_DEVICE_TYPE, &deviceType); if(stat==SM_OK && busMode==0)//busmode 0 is DFU mode { diff --git a/devicedeployment.h b/devicedeployment.h index d151579..696d4a8 100644 --- a/devicedeployment.h +++ b/devicedeployment.h @@ -94,7 +94,7 @@ LIB void smFirmwareUploadStatusToString(const FirmwareUploadStatus FWUploadStatu * @param fwDataLenght number of bytes in fwData * @return Enum FirmwareUploadStatus that indicates errors or Complete status. Typecast to integer to get progress value 0-100. */ -FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int smaddress, smuint8 *fwData, const int fwDataLength ); +FirmwareUploadStatus smFirmwareUploadFromBuffer( const smbus smhandle, const int smaddress, uint8_t *fwData, const int fwDataLength ); typedef enum { @@ -143,7 +143,7 @@ LIB LoadConfigurationStatus smLoadConfiguration( const smbus smhandle, const int * * Requires DRC file version 111 or later to use CONFIGMODE_REQUIRE_SAME_FW. */ -LIB LoadConfigurationStatus smLoadConfigurationFromBuffer(const smbus smhandle, const int smaddress, const smuint8 *drcData, const int drcDataLength, unsigned int mode, int *skippedCount, int *errorCount ); +LIB LoadConfigurationStatus smLoadConfigurationFromBuffer(const smbus smhandle, const int smaddress, const uint8_t *drcData, const int drcDataLength, unsigned int mode, int *skippedCount, int *errorCount ); /** @@ -153,7 +153,7 @@ LIB LoadConfigurationStatus smLoadConfigurationFromBuffer(const smbus smhandle, * @param UID result will be written to this pointer * @return true if success, false if failed (if communication otherwise works, then probably UID feature not present in this firmware version) */ -bool smGetDeviceFirmwareUniqueID( smbus smhandle, int deviceaddress, smuint32 *UID ); +bool smGetDeviceFirmwareUniqueID( smbus smhandle, int deviceaddress, uint32_t *UID ); #ifdef __cplusplus diff --git a/simplemotion.c b/simplemotion.c index fc37ad5..2b6fb75 100644 --- a/simplemotion.c +++ b/simplemotion.c @@ -12,7 +12,7 @@ #include "simplemotion_private.h" -SM_STATUS smParseReturnData( smbus handle, smuint8 data ); +SM_STATUS smParseReturnData( smbus handle, uint8_t data ); #define HANDLE_STAT(stat) if(stat!=SM_OK)return (stat); #define HANDLE_STAT_AND_RET(stat,returndata) { if(returndata==RET_INVALID_CMD||returndata==RET_INVALID_PARAM) return SM_ERR_PARAMETER; if(stat!=SM_OK) return (stat); } @@ -21,12 +21,12 @@ enum RecvState {WaitCmdId,WaitAddr,WaitPayloadSize,WaitPayload,WaitCrcHi,WaitCrc FILE *smDebugOut=NULL; //useful macros from extracting/storing multibyte values from/to byte buffer -#define bufput32bit(buf, pos, val) *((smuint32*)(smuint8*)((buf)+(pos)))=((smuint32)(val)) -#define bufput16bit(buf, pos, val) *((smuint16*)(smuint8*)((buf)+(pos)))=((smuint16)(val)) -#define bufput8bit(buf, pos, val) *((smuint8*)(smuint8*)((buf)+(pos)))=((smuint8)(val)) -#define bufget32bit(buf, pos) (*((smuint32*)(smuint8*)((buf)+(pos)))) -#define bufget16bit(buf, pos) (*((smuint16*)(smuint8*)((buf)+(pos)))) -#define bufget8bit(buf, pos) (*((smuint8*)(smuint8*)((buf)+(pos)))) +#define bufput32bit(buf, pos, val) *((uint32_t*)(uint8_t*)((buf)+(pos)))=((uint32_t)(val)) +#define bufput16bit(buf, pos, val) *((uint16_t*)(uint8_t*)((buf)+(pos)))=((uint16_t)(val)) +#define bufput8bit(buf, pos, val) *((uint8_t*)(uint8_t*)((buf)+(pos)))=((uint8_t)(val)) +#define bufget32bit(buf, pos) (*((uint32_t*)(uint8_t*)((buf)+(pos)))) +#define bufget16bit(buf, pos) (*((uint16_t*)(uint8_t*)((buf)+(pos)))) +#define bufget8bit(buf, pos) (*((uint8_t*)(uint8_t*)((buf)+(pos)))) bool smIsHandleOpen( const smbus handle ); @@ -40,19 +40,19 @@ typedef struct SM_BUS_ enum RecvState recv_state,recv_state_next; - smint16 recv_payloadsize; - smint16 recv_storepos; - smuint8 recv_rsbuf[SM485_RSBUFSIZE]; - smuint8 recv_cmdid; - smuint8 recv_addr; - smuint16 recv_crc; - smuint16 recv_read_crc_hi; + int16_t recv_payloadsize; + int16_t recv_storepos; + uint8_t recv_rsbuf[SM485_RSBUFSIZE]; + uint8_t recv_cmdid; + uint8_t recv_addr; + uint16_t recv_crc; + uint16_t recv_read_crc_hi; bool receiveComplete; bool transmitBufFull;//set true if user uploads too much commands in one SM transaction. if true, on execute commands, nothing will be sent to bus to prevent unvanted clipped commands and buffer will be cleared char busDeviceName[SM_BUSDEVICENAME_LEN]; - smint16 cmd_send_queue_bytes;//for queued device commands - smint16 cmd_recv_queue_bytes;//recv_queue_bytes counted upwards at every smGetQueued.. and compared to payload size + int16_t cmd_send_queue_bytes;//for queued device commands + int16_t cmd_recv_queue_bytes;//recv_queue_bytes counted upwards at every smGetQueued.. and compared to payload size SM_STATUS cumulativeSmStatus; @@ -60,7 +60,7 @@ typedef struct SM_BUS_ SM_BUS smBus[SM_MAX_BUSES]; -smuint16 readTimeoutMs=SM_READ_TIMEOUT; +uint16_t readTimeoutMs=SM_READ_TIMEOUT; //init on first smOpenBus call bool smInitialized=false; @@ -145,7 +145,7 @@ void smResetSM485variables(smbus handle) smBus[handle].cmd_recv_queue_bytes=0; } -smuint16 calcCRC16(smuint8 data, smuint16 crc) +uint16_t calcCRC16(uint8_t data, uint16_t crc) { unsigned int i; /* will index into CRC lookup */ @@ -155,10 +155,10 @@ smuint16 calcCRC16(smuint8 data, smuint16 crc) return crc; } -smuint16 calcCRC16Buf(const char *buffer, smuint16 buffer_length) +uint16_t calcCRC16Buf(const char *buffer, uint16_t buffer_length) { - smuint8 crc_hi = 0xFF; /* high CRC byte initialized */ - smuint8 crc_lo = 0xFF; /* low CRC byte initialized */ + uint8_t crc_hi = 0xFF; /* high CRC byte initialized */ + uint8_t crc_lo = 0xFF; /* low CRC byte initialized */ unsigned int i; /* will index into CRC lookup */ /* pass through message buffer */ @@ -171,10 +171,10 @@ smuint16 calcCRC16Buf(const char *buffer, smuint16 buffer_length) return (crc_hi << 8 | crc_lo); } -smuint8 calcCRC8Buf( smuint8 *buf, int len, int crcinit ) +uint8_t calcCRC8Buf( uint8_t *buf, int len, int crcinit ) { int i; - smuint8 crc=crcinit; + uint8_t crc=crcinit; for(i=0;i=1) { @@ -194,7 +194,7 @@ SM_STATUS smSetTimeout( smuint16 millsecs ) return SM_ERR_PARAMETER; } -smuint32 smGetVersion() +uint32_t smGetVersion() { return SM_VERSION; } @@ -345,7 +345,7 @@ LIB SM_STATUS smFlushTX( const smbus bushandle ) } -char *cmdidToStr(smuint8 cmdid ) +char *cmdidToStr(uint8_t cmdid ) { char *str; switch(cmdid) @@ -372,7 +372,7 @@ char *cmdidToStr(smuint8 cmdid ) //write one byte to tx buffer //returns true on success -bool smWriteByte( const smbus handle, const smuint8 byte, smuint16 *crc ) +bool smWriteByte( const smbus handle, const uint8_t byte, uint16_t *crc ) { //check if bus handle is valid & opened if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; @@ -395,10 +395,10 @@ bool smTransmitBuffer( const smbus handle ) return success; } -SM_STATUS smSendSMCMD( smbus handle, smuint8 cmdid, smuint8 addr, smuint8 datalen, smuint8 *cmddata ) +SM_STATUS smSendSMCMD( smbus handle, uint8_t cmdid, uint8_t addr, uint8_t datalen, uint8_t *cmddata ) { int i; - smuint16 sendcrc; + uint16_t sendcrc; //check if bus handle is valid & opened if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; @@ -439,13 +439,13 @@ SM_STATUS smSendSMCMD( smbus handle, smuint8 cmdid, smuint8 addr, smuint8 datale return recordStatus(handle,SM_OK); } -LIB SM_STATUS smFastUpdateCycleWithStructs( smbus handle, smuint8 nodeAddress, FastUpdateCycleWriteData write, FastUpdateCycleReadData *read) +LIB SM_STATUS smFastUpdateCycleWithStructs( smbus handle, uint8_t nodeAddress, FastUpdateCycleWriteData write, FastUpdateCycleReadData *read) { return smFastUpdateCycle( handle, nodeAddress, write.U16[0], write.U16[1], &read->U16[0], &read->U16[1]); } -SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, smuint16 write2, smuint16 *read1, smuint16 *read2) +SM_STATUS smFastUpdateCycle( smbus handle, uint8_t nodeAddress, uint16_t write1, uint16_t write2, uint16_t *read1, uint16_t *read2) { //check if bus handle is valid & opened if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; @@ -456,7 +456,7 @@ SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, //form the tx packet - smuint8 cmd[8]; + uint8_t cmd[8]; int i; cmd[0]=SMCMD_FAST_UPDATE_CYCLE; cmd[1]=nodeAddress; @@ -476,7 +476,7 @@ SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, for(i=0;i<6;i++) { bool success; - smuint8 rx; + uint8_t rx; success=smBDRead(smBus[handle].bdHandle,&rx); cmd[i]=rx; if(!success) @@ -487,7 +487,7 @@ SM_STATUS smFastUpdateCycle( smbus handle, smuint8 nodeAddress, smuint16 write1, } //parse - smuint8 localCRC=calcCRC8Buf(cmd,5,0x52); + uint8_t localCRC=calcCRC8Buf(cmd,5,0x52); if( cmd[5]!=localCRC|| cmd[0]!=SMCMD_FAST_UPDATE_CYCLE_RET ) { smDebug(handle,SMDebugLow,"Corrupt data received on smFastUpdateCycle. RX CRC %02x (expected %02x), RX ID %02x, (expected %02x)\n",cmd[5],localCRC,cmd[0],SMCMD_FAST_UPDATE_CYCLE_RET); @@ -519,7 +519,7 @@ SM_STATUS smReceiveErrorHandler( smbus handle, bool flushrx ) { bool success; do{ - smuint8 rx; + uint8_t rx; success=smBDRead(smBus[handle].bdHandle,&rx); }while(success); } @@ -529,7 +529,7 @@ SM_STATUS smReceiveErrorHandler( smbus handle, bool flushrx ) } -SM_STATUS smAppendSMCommandToQueue( smbus handle, int smpCmdType,smint32 paramvalue ) +SM_STATUS smAppendSMCommandToQueue( smbus handle, int smpCmdType,int32_t paramvalue ) { int cmdlength; @@ -601,7 +601,7 @@ SMPayloadCommandRet32 smConvertToPayloadRet32_16(SMPayloadCommandRet16 in) } //for library internal use only -SM_STATUS smTransmitReceiveCommandQueue( const smbus bushandle, const smaddr targetaddress, smuint8 cmdid ) +SM_STATUS smTransmitReceiveCommandQueue( const smbus bushandle, const smaddr targetaddress, uint8_t cmdid ) { SM_STATUS stat; @@ -648,19 +648,19 @@ SM_STATUS smUploadCommandQueueToDeviceBuffer( const smbus bushandle, const smadd } //return number of how many bytes waiting to be read with smGetQueuedSMCommandReturnValue -SM_STATUS smBytesReceived( const smbus bushandle, smint32 *bytesinbuffer ) +SM_STATUS smBytesReceived( const smbus bushandle, int32_t *bytesinbuffer ) { if(!smIsHandleOpen(bushandle)) return recordStatus(bushandle,SM_ERR_NODEVICE); - smint32 bytes=smBus[bushandle].recv_payloadsize - smBus[bushandle].cmd_recv_queue_bytes;//how many bytes waiting to be read with smGetQueuedSMCommandReturnValue + int32_t bytes=smBus[bushandle].recv_payloadsize - smBus[bushandle].cmd_recv_queue_bytes;//how many bytes waiting to be read with smGetQueuedSMCommandReturnValue *bytesinbuffer=bytes; return recordStatus(bushandle,SM_OK); } -SM_STATUS smGetQueuedSMCommandReturnValue( const smbus bushandle, smint32 *retValue ) +SM_STATUS smGetQueuedSMCommandReturnValue( const smbus bushandle, int32_t *retValue ) { - smuint8 rxbyte, rettype; + uint8_t rxbyte, rettype; //check if bus handle is valid & opened if(!smIsHandleOpen(bushandle)) return SM_ERR_NODEVICE; @@ -688,7 +688,7 @@ SM_STATUS smGetQueuedSMCommandReturnValue( const smbus bushandle, smint32 *retV { //extract return packet and convert to 32 bit and return SMPayloadCommandRet16 read; - smuint8 *readBuf=(smuint8*)&read; + uint8_t *readBuf=(uint8_t*)&read; readBuf[1]=rxbyte; readBuf[0]=bufget8bit(smBus[bushandle].recv_rsbuf, smBus[bushandle].cmd_recv_queue_bytes++); smDebug(bushandle,SMDebugTrace," RET16B: %d\n",read.retData); @@ -700,7 +700,7 @@ SM_STATUS smGetQueuedSMCommandReturnValue( const smbus bushandle, smint32 *retV { //extract return packet and convert to 32 bit and return SMPayloadCommandRet24 read; - smuint8 *readBuf=(smuint8*)&read; + uint8_t *readBuf=(uint8_t*)&read; readBuf[2]=rxbyte; readBuf[1]=bufget8bit(smBus[bushandle].recv_rsbuf, smBus[bushandle].cmd_recv_queue_bytes++); readBuf[0]=bufget8bit(smBus[bushandle].recv_rsbuf, smBus[bushandle].cmd_recv_queue_bytes++); @@ -713,7 +713,7 @@ SM_STATUS smGetQueuedSMCommandReturnValue( const smbus bushandle, smint32 *retV { //extract return packet and convert to 32 bit and return SMPayloadCommandRet32 read; - smuint8 *readBuf=(smuint8*)&read; + uint8_t *readBuf=(uint8_t*)&read; readBuf[3]=rxbyte; readBuf[2]=bufget8bit(smBus[bushandle].recv_rsbuf, smBus[bushandle].cmd_recv_queue_bytes++); readBuf[1]=bufget8bit(smBus[bushandle].recv_rsbuf, smBus[bushandle].cmd_recv_queue_bytes++); @@ -727,7 +727,7 @@ SM_STATUS smGetQueuedSMCommandReturnValue( const smbus bushandle, smint32 *retV { //extract return packet and convert to 32 bit and return SMPayloadCommandRet8 read; - smuint8 *readBuf=(smuint8*)&read; + uint8_t *readBuf=(uint8_t*)&read; readBuf[0]=rxbyte; smDebug(bushandle,SMDebugTrace," RET_OTHER: %d\n",read.retData); @@ -747,7 +747,7 @@ SM_STATUS smReceiveReturnPacket( smbus bushandle ) smDebug(bushandle, SMDebugHigh, " Reading reply packet\n"); do { - smuint8 ret; + uint8_t ret; SM_STATUS stat; bool succ=smBDRead(smBus[bushandle].bdHandle,&ret); @@ -783,7 +783,7 @@ LIB void smSetDebugOutput( smVerbosityLevel level, FILE *stream ) //short returndata16=0, payload=0; //can be called at any frequency -SM_STATUS smParseReturnData( smbus handle, smuint8 data ) +SM_STATUS smParseReturnData( smbus handle, uint8_t data ) { //check if bus handle is valid & opened if(!smIsHandleOpen(handle)) return SM_ERR_NODEVICE; @@ -883,7 +883,7 @@ SM_STATUS smParseReturnData( smbus handle, smuint8 data ) //reply consumes 16 bytes in payload buf, so max calls per cycle is 7 -SM_STATUS smAppendGetParamCommandToQueue( smbus handle, smint16 paramAddress ) +SM_STATUS smAppendGetParamCommandToQueue( smbus handle, int16_t paramAddress ) { SM_STATUS stat=SM_NONE; @@ -900,9 +900,9 @@ SM_STATUS smAppendGetParamCommandToQueue( smbus handle, smint16 paramAddress ) return recordStatus(handle,stat); } -SM_STATUS smGetQueuedGetParamReturnValue( const smbus bushandle, smint32 *retValue ) +SM_STATUS smGetQueuedGetParamReturnValue( const smbus bushandle, int32_t *retValue ) { - smint32 retVal=0; + int32_t retVal=0; SM_STATUS stat=SM_NONE; //check if bus handle is valid & opened @@ -918,7 +918,7 @@ SM_STATUS smGetQueuedGetParamReturnValue( const smbus bushandle, smint32 *retVa } //consumes 6 bytes in payload buf, so max calls per cycle is 20 -SM_STATUS smAppendSetParamCommandToQueue( smbus handle, smint16 paramAddress, smint32 paramValue ) +SM_STATUS smAppendSetParamCommandToQueue( smbus handle, int16_t paramAddress, int32_t paramValue ) { SM_STATUS stat=SM_NONE; @@ -931,9 +931,9 @@ SM_STATUS smAppendSetParamCommandToQueue( smbus handle, smint16 paramAddress, sm } -SM_STATUS smGetQueuedSetParamReturnValue( const smbus bushandle, smint32 *retValue ) +SM_STATUS smGetQueuedSetParamReturnValue( const smbus bushandle, int32_t *retValue ) { - smint32 retVal=0; + int32_t retVal=0; SM_STATUS stat=SM_NONE; //check if bus handle is valid & opened @@ -948,7 +948,7 @@ SM_STATUS smGetQueuedSetParamReturnValue( const smbus bushandle, smint32 *retVa } -SM_STATUS smGetBufferClock( const smbus handle, const smaddr targetaddr, smuint16 *clock ) +SM_STATUS smGetBufferClock( const smbus handle, const smaddr targetaddr, uint16_t *clock ) { SM_STATUS stat; @@ -964,7 +964,7 @@ SM_STATUS smGetBufferClock( const smbus handle, const smaddr targetaddr, smuint1 if(stat!=SM_OK) return recordStatus(handle,stat); //maybe timeouted if(clock!=NULL) - memcpy(clock,smBus[handle].recv_rsbuf,sizeof(smuint16)); + memcpy(clock,smBus[handle].recv_rsbuf,sizeof(uint16_t)); smBus[handle].recv_storepos=0; @@ -973,7 +973,7 @@ SM_STATUS smGetBufferClock( const smbus handle, const smaddr targetaddr, smuint1 /** Simple read & write of parameters with internal queueing, so only one call needed. Use these for non-time critical operations. */ -SM_STATUS smRead1Parameter( const smbus handle, const smaddr nodeAddress, const smint16 paramId1, smint32 *paramVal1 ) +SM_STATUS smRead1Parameter( const smbus handle, const smaddr nodeAddress, const int16_t paramId1, int32_t *paramVal1 ) { SM_STATUS smStat=0; @@ -991,7 +991,7 @@ SM_STATUS smRead1Parameter( const smbus handle, const smaddr nodeAddress, const return recordStatus(handle,smStat); } -SM_STATUS smRead2Parameters( const smbus handle, const smaddr nodeAddress, const smint16 paramId1, smint32 *paramVal1,const smint16 paramId2, smint32 *paramVal2 ) +SM_STATUS smRead2Parameters( const smbus handle, const smaddr nodeAddress, const int16_t paramId1, int32_t *paramVal1,const int16_t paramId2, int32_t *paramVal2 ) { SM_STATUS smStat=0; @@ -1011,7 +1011,7 @@ SM_STATUS smRead2Parameters( const smbus handle, const smaddr nodeAddress, const return recordStatus(handle,smStat); } -SM_STATUS smRead3Parameters( const smbus handle, const smaddr nodeAddress, const smint16 paramId1, smint32 *paramVal1,const smint16 paramId2, smint32 *paramVal2 ,const smint16 paramId3, smint32 *paramVal3 ) +SM_STATUS smRead3Parameters( const smbus handle, const smaddr nodeAddress, const int16_t paramId1, int32_t *paramVal1,const int16_t paramId2, int32_t *paramVal2 ,const int16_t paramId3, int32_t *paramVal3 ) { SM_STATUS smStat=0; @@ -1033,9 +1033,9 @@ SM_STATUS smRead3Parameters( const smbus handle, const smaddr nodeAddress, const return recordStatus(handle,smStat); } -SM_STATUS smSetParameter( const smbus handle, const smaddr nodeAddress, const smint16 paramId, smint32 paramVal ) +SM_STATUS smSetParameter( const smbus handle, const smaddr nodeAddress, const int16_t paramId, int32_t paramVal ) { - smint32 nul; + int32_t nul; SM_STATUS smStat=0; smDebug(handle,SMDebugMid,"smSetParameter: writing parameter [%hu]=%d into SM address %d.\n",(unsigned short)paramId,(int)paramVal,(int)nodeAddress); @@ -1089,14 +1089,14 @@ SM_STATUS resetCumulativeStatus( const smbus handle ) /** Return number of bus devices found. details of each device may be consequently fetched by smGetBusDeviceDetails() */ -smint smGetNumberOfDetectedBuses() +int smGetNumberOfDetectedBuses() { return smBDGetNumberOfDetectedBuses(); } /** Fetch information of detected bus nodes at certain index. Example: - smint num=smGetNumberOfDetectedBuses(); + int num=smGetNumberOfDetectedBuses(); for(int i=0;iNEWEST_SUPPORTED_SMV2_VERSION && smv2compatversion>NEWEST_SUPPORTED_SMV2_VERSION) { @@ -375,7 +375,7 @@ /* SMP_BINARY_DATA_MODE_ARGS is a helper macro to generate value for SMP_BINARY_DATA_MODE. Example: * smSetParameter( .., .., SMP_BINARY_DATA_MODE, SMP_BINARY_DATA_MODE_ARGS( BINARY_DATA_MODE_BLOCK_CALIBRATION, BINARY_DATA_MODE_FLAG_ERASE, 500 ) */ -#define SMP_BINARY_DATA_MODE_ARGS(block,flags,offset) ((smuint32(block)&0xff) | (smuint32(flags)&0xff00) | ((smuint32(offset)<<16)&0xffff0000)) +#define SMP_BINARY_DATA_MODE_ARGS(block,flags,offset) ((uint32_t(block)&0xff) | (uint32_t(flags)&0xff00) | ((uint32_t(offset)<<16)&0xffff0000)) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SimpleMotion device specific parameter definitions start below. Note: all parameters are not available in all device types/versions. To test which are available, diff --git a/simplemotion_private.h b/simplemotion_private.h index aa0cdde..f68c6b0 100644 --- a/simplemotion_private.h +++ b/simplemotion_private.h @@ -25,11 +25,11 @@ extern unsigned long SMBusBaudrate; //the next opened port (with smOpenBus) will #define SM_READ_TIMEOUT 500 -extern const smuint8 table_crc16_hi[]; -extern const smuint8 table_crc16_lo[]; -extern const smuint8 table_crc8[]; +extern const uint8_t table_crc16_hi[]; +extern const uint8_t table_crc16_lo[]; +extern const uint8_t table_crc8[]; extern FILE *smDebugOut; //such as stderr or file handle. if NULL, debug info disbled -extern smuint16 readTimeoutMs; +extern uint16_t readTimeoutMs; #define DEBUG_PRINT_RAW 0x524157 //smDebug: prints debug info to smDebugOut stream. If no handle available, set it to -1, or if wish to print as raw text, set handle to DEBUG_PRINT_RAW. @@ -44,7 +44,7 @@ void smDebug( smbus handle, smVerbosityLevel verbositylevel, char *format, ...); //accumulates status to internal variable by ORing the bits. returns same value that is fed as paramter SM_STATUS recordStatus( const smbus handle, const SM_STATUS stat ); -SM_STATUS smRawCmd( const char *axisname, smuint8 cmd, smuint16 val, smuint32 *retdata ); +SM_STATUS smRawCmd( const char *axisname, uint8_t cmd, uint16_t val, uint32_t *retdata ); /*Workaround to have packed structs that compile on GCC and MSVC*/ #ifdef __GNUC__ @@ -130,9 +130,9 @@ typedef struct { typedef union { - smuint8 U8[4]; - smuint16 U16[2]; - smuint32 U32; + uint8_t U8[4]; + uint16_t U16[2]; + uint32_t U32; } UnionOf4Bytes; /*Workaround to have packed structs that compile on GCC and MSVC*/ diff --git a/simplemotion_types.h b/simplemotion_types.h index 09523f2..dd25afd 100644 --- a/simplemotion_types.h +++ b/simplemotion_types.h @@ -24,14 +24,14 @@ typedef uint8_t smuint8; typedef int32_t smint32; typedef int16_t smint16; typedef int8_t smint8; -typedef smint32 smint; +typedef int32_t smint; typedef bool smbool; // These are kept only for legacy compatibility; use for better versions #define smtrue 1 #define smfalse 0 typedef int SM_STATUS; -typedef smuint8 smaddr; +typedef uint8_t smaddr; // output parameter type of smGetBusDeviceDetails typedef struct @@ -64,9 +64,9 @@ typedef enum _BusDeviceMiscOperationType {MiscOperationFlushTX,MiscOperationPurg //define communication interface device driver callback types typedef void* smBusdevicePointer; -typedef smBusdevicePointer (*BusdeviceOpen)(const char *port_device_name, smint32 baudrate_bps, bool *success); -typedef smint32 (*BusdeviceReadBuffer)(smBusdevicePointer busdevicePointer, unsigned char *buf, smint32 size); -typedef smint32 (*BusdeviceWriteBuffer)(smBusdevicePointer busdevicePointer, unsigned char *buf, smint32 size); +typedef smBusdevicePointer (*BusdeviceOpen)(const char *port_device_name, int32_t baudrate_bps, bool *success); +typedef int32_t (*BusdeviceReadBuffer)(smBusdevicePointer busdevicePointer, unsigned char *buf, int32_t size); +typedef int32_t (*BusdeviceWriteBuffer)(smBusdevicePointer busdevicePointer, unsigned char *buf, int32_t size); typedef bool (*BusdeviceMiscOperation)(smBusdevicePointer busdevicePointer, BusDeviceMiscOperationType operation ); typedef void (*BusdeviceClose)(smBusdevicePointer busdevicePointer); @@ -77,52 +77,52 @@ typedef void (*BusdeviceClose)(smBusdevicePointer busdevicePointer); typedef union { //raw data - smuint8 U8[4]; - smuint16 U16[2]; - smuint32 U32; + uint8_t U8[4]; + uint16_t U16[2]; + uint32_t U32; //use this when SMP_FAST_UPDATE_CYCLE_FORMAT = FAST_UPDATE_CYCLE_FORMAT_DEFAULT struct { - smint32 SetPoint:16; - smuint32 _unused:16; + int32_t SetPoint:16; + uint32_t _unused:16; } DEFAULT_Write; //use this when SMP_FAST_UPDATE_CYCLE_FORMAT = FAST_UPDATE_CYCLE_FORMAT_ALT1 struct { - smint32 Setpoint:28; - smuint32 CB1_Enable:1; - smuint32 CB1_ClearFaults:1; - smuint32 CB1_QuickStopSet:1; - smuint32 CB1_BypassTrajPlanner:1; + int32_t Setpoint:28; + uint32_t CB1_Enable:1; + uint32_t CB1_ClearFaults:1; + uint32_t CB1_QuickStopSet:1; + uint32_t CB1_BypassTrajPlanner:1; } ALT1_Write; //use this when SMP_FAST_UPDATE_CYCLE_FORMAT = FAST_UPDATE_CYCLE_FORMAT_ALT2 struct { - smint32 SetpointMainTorque:15; - smint32 SetpointEffectTorque:15; - smuint32 CB1_Enable:1; - smuint32 CB1_Clearfaults:1; + int32_t SetpointMainTorque:15; + int32_t SetpointEffectTorque:15; + uint32_t CB1_Enable:1; + uint32_t CB1_Clearfaults:1; } ALT2_Write; //use this when SMP_FAST_UPDATE_CYCLE_FORMAT = FAST_UPDATE_CYCLE_FORMAT_ALT3 struct { - smint32 SetpointMainTorque:15; - smint32 SetpointEffectTorque:15; - smuint32 CB1_Enable:1; - smuint32 CB1_Clearfaults:1; + int32_t SetpointMainTorque:15; + int32_t SetpointEffectTorque:15; + uint32_t CB1_Enable:1; + uint32_t CB1_Clearfaults:1; } ALT3_Write; //use this when SMP_FAST_UPDATE_CYCLE_FORMAT = FAST_UPDATE_CYCLE_FORMAT_ALT4 struct { - smint32 SetpointMainTorque:15; - smint32 SetpointEffectTorque:15; - smuint32 CB1_Enable:1; - smuint32 CB1_Clearfaults:1; + int32_t SetpointMainTorque:15; + int32_t SetpointEffectTorque:15; + uint32_t CB1_Enable:1; + uint32_t CB1_Clearfaults:1; } ALT4_Write; } FastUpdateCycleWriteData; @@ -130,41 +130,41 @@ typedef union typedef union { //raw data - smuint8 U8[4]; - smuint16 U16[2]; - smuint32 U32; + uint8_t U8[4]; + uint16_t U16[2]; + uint32_t U32; //use this when SMP_FAST_UPDATE_CYCLE_FORMAT = FAST_UPDATE_CYCLE_FORMAT_DEFAULT struct { - smint32 PositionFeedback:16; - smuint32 StatusRegister:16; + int32_t PositionFeedback:16; + uint32_t StatusRegister:16; } DEFAULT_Read; //use this when SMP_FAST_UPDATE_CYCLE_FORMAT = FAST_UPDATE_CYCLE_FORMAT_ALT1 or FAST_UPDATE_CYCLE_FORMAT_ALT2 struct { - smint32 PositionFeedback:30; - smuint32 Stat_FaultStop:1; - smuint32 Stat_ServoReady:1; + int32_t PositionFeedback:30; + uint32_t Stat_FaultStop:1; + uint32_t Stat_ServoReady:1; } ALT1_ALT2_Read; //use this when SMP_FAST_UPDATE_CYCLE_FORMAT = FAST_UPDATE_CYCLE_FORMAT_ALT1 or FAST_UPDATE_CYCLE_FORMAT_ALT3 struct { - smint32 PositionFeedback:24; - smuint32 PositionFeedbackSamplingTimestamp:6; //encoder sampling cycle, 400 us periods - smuint32 Stat_FaultStop:1; - smuint32 Stat_ServoReady:1; + int32_t PositionFeedback:24; + uint32_t PositionFeedbackSamplingTimestamp:6; //encoder sampling cycle, 400 us periods + uint32_t Stat_FaultStop:1; + uint32_t Stat_ServoReady:1; } ALT3_Read; //use this when SMP_FAST_UPDATE_CYCLE_FORMAT = FAST_UPDATE_CYCLE_FORMAT_ALT1 or FAST_UPDATE_CYCLE_FORMAT_ALT4 struct { - smuint32 PositionFeedback:24; // scale is full 24 bits per motor revolution. is not hard absolute like it's in ALT3, and will reset to 0 in centering and with offset SMP. - smuint32 PositionFeedbackSamplingTimestamp:6; //encoder sampling cycle, 400 us periods - smuint32 Stat_FaultStop:1; - smuint32 Stat_ServoReady:1; + uint32_t PositionFeedback:24; // scale is full 24 bits per motor revolution. is not hard absolute like it's in ALT3, and will reset to 0 in centering and with offset SMP. + uint32_t PositionFeedbackSamplingTimestamp:6; //encoder sampling cycle, 400 us periods + uint32_t Stat_FaultStop:1; + uint32_t Stat_ServoReady:1; } ALT4_Read; } FastUpdateCycleReadData; diff --git a/sm_consts.c b/sm_consts.c index 62439af..ec00273 100644 --- a/sm_consts.c +++ b/sm_consts.c @@ -2,7 +2,7 @@ /* Table of CRC16 values for high-order byte */ -const smuint8 table_crc16_hi[] = { +const uint8_t table_crc16_hi[] = { 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, @@ -31,7 +31,7 @@ const smuint8 table_crc16_hi[] = { 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 }; /* Table of CRC16 values for low-order byte */ -const smuint8 table_crc16_lo[] = { +const uint8_t table_crc16_lo[] = { 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, @@ -61,7 +61,7 @@ const smuint8 table_crc16_lo[] = { }; //http://www.maxim-ic.com/appnotes.cfm/an_pk/3749 -const smuint8 table_crc8[] = { +const uint8_t table_crc8[] = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, From 3faff85e060acc2c4277a4046bda107022f6ffb2 Mon Sep 17 00:00:00 2001 From: Joonas Koivunen Date: Sat, 9 Nov 2019 21:04:57 +0200 Subject: [PATCH 07/11] refactor fix some warnings --- busdevice.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/busdevice.c b/busdevice.c index 7f688a0..f5d9c48 100644 --- a/busdevice.c +++ b/busdevice.c @@ -225,8 +225,9 @@ int smBDGetNumberOfDetectedBuses() //only supports FTDI D2XX at the moment #ifdef FTDI_D2XX_SUPPORT return d2xxGetNumberOfDetectedBuses(); -#endif +#else return 0; +#endif } bool smBDGetBusDeviceDetails( int index, SM_BUS_DEVICE_INFO *info ) @@ -234,7 +235,10 @@ bool smBDGetBusDeviceDetails( int index, SM_BUS_DEVICE_INFO *info ) //only supports FTDI D2XX at the moment #ifdef FTDI_D2XX_SUPPORT return d2xxGetBusDeviceDetails(index,info); -#endif +#else + (void)index; + (void)info; return false; +#endif } From 900bcfeed14ff753888a2195715ed0e8fc7b167f Mon Sep 17 00:00:00 2001 From: Joonas Koivunen Date: Sat, 9 Nov 2019 21:07:35 +0200 Subject: [PATCH 08/11] refactor fix unused memory read --- devicedeployment.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/devicedeployment.c b/devicedeployment.c index 14250d1..c18f6a2 100755 --- a/devicedeployment.c +++ b/devicedeployment.c @@ -596,7 +596,7 @@ bool smGetDeviceFirmwareUniqueID( smbus smhandle, int deviceaddress, uint32_t *U uint8_t bufferGet8( uint8_t **buf ) { uint8_t ret=(*buf)[0]; - *buf++; + buf++; return ret; } From a64da1c7ec2603fc0de631d755a49a3ec26fce89 Mon Sep 17 00:00:00 2001 From: Joonas Koivunen Date: Sat, 9 Nov 2019 21:18:18 +0200 Subject: [PATCH 09/11] refactor fix remove unused local variables --- devicedeployment.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/devicedeployment.c b/devicedeployment.c index c18f6a2..9842072 100755 --- a/devicedeployment.c +++ b/devicedeployment.c @@ -241,9 +241,6 @@ bool parseDRCIntKey( const uint8_t *drcData, const int drcDataLen, const char *k //read DRC file version nr and nubmer of params it contains. if succes, returns true. if invalid file, return false bool parseDRCInfo( const uint8_t *drcData, const int drcDataLen, int *DRCVersion, int *numParams, int *DRCFileFeatureBits, int *DRCEssentialFileFeatureBits ) { - const char *DRCFileFeatureBitsKey="FileFeatureBits="; - const char *DRCEssentialFileFeatureBitsKey="FileFeatureBitsEssential="; - if(!parseDRCIntKey(drcData,drcDataLen,"DRCVersion=",DRCVersion)) return false; //parse failed if(!parseDRCIntKey(drcData,drcDataLen,"size=",numParams)) return false; //parse failed From 1f2a93c68616e62d616fc993b6d6d883642e1278 Mon Sep 17 00:00:00 2001 From: Joonas Koivunen Date: Sat, 9 Nov 2019 21:27:45 +0200 Subject: [PATCH 10/11] chore reorder smbus typedef away from legacy defs --- simplemotion_types.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/simplemotion_types.h b/simplemotion_types.h index dd25afd..f979c8d 100644 --- a/simplemotion_types.h +++ b/simplemotion_types.h @@ -16,8 +16,7 @@ #define SM_ERR_PARAMETER 16 #define SM_ERR_LENGTH 32 -//declare SM lib integer types -typedef long smbus; +// These are kept only for legacy compatibility and will eventually be removed. Use for real versions. typedef uint32_t smuint32; typedef uint16_t smuint16; typedef uint8_t smuint8; @@ -27,9 +26,11 @@ typedef int8_t smint8; typedef int32_t smint; typedef bool smbool; -// These are kept only for legacy compatibility; use for better versions +// These are kept only for legacy compatibility and will eventually be removed. Use for better versions. #define smtrue 1 #define smfalse 0 + +typedef long smbus; typedef int SM_STATUS; typedef uint8_t smaddr; From 2c710a343117461ea2eacdec79397019a3d79382 Mon Sep 17 00:00:00 2001 From: Joonas Koivunen Date: Sat, 9 Nov 2019 21:40:47 +0200 Subject: [PATCH 11/11] chore select c99 as the std c11 is the gcc default in mainstream distributions, but this is the minimum version for stdint, inttypes and stdbool. former two were already used in the library. --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 50bcacd..8e71900 100644 --- a/Makefile +++ b/Makefile @@ -9,7 +9,7 @@ OBJECTS = $(SOURCES:%.c=%.o) #user optionsare the ones starting with -D below #be sure to check also user_options.h for more CPPFLAGS = -I. -Iutils/ -DENABLE_BUILT_IN_DRIVERS -CFLAGS = -Wall -Wextra -DENABLE_BUILT_IN_DRIVERS -Iutils/ +CFLAGS = -std=c99 -Wall -Wextra -DENABLE_BUILT_IN_DRIVERS -Iutils/ all: libsimplemotionv2.a